我想用代码在工程中动态地加载控件,
请问各位大虾我应该如何编写代码????

解决方案 »

  1.   

    Private Sub Form_Load()
       Form1.Controls.Add "VB.CommandButton", "cmdObj1", Frame1
       With Form1!cmdObj1
          .Visible = True
          .Width = 2000
          .Caption = "Dynamic Button"
       End With
    End Sub注意 上面的代码例子使用 ! 作为一个语法要素。您也可以使用标准集合语法如 Form1.Controls("cmdObj1") 来引用该控件。第二个例子使用 WithEvents 关键字声明一个 CommandButton 类型的对象变量,允许您编程该控件的事件。对象变量被设置为由 Add 方法返回的引用。要试验该例,把它的代码粘贴到声明部分并且运行该工程。Option Explicit
    Private WithEvents btnObj As CommandButtonPrivate Sub btnObj_Click()
       MsgBox "This is a dynamically added button."
    End SubPrivate Sub Form_Load()
       Set btnObj = Controls.Add("VB.CommandButton", "btnObj")
       With btnObj
          .Visible = True
          .Width = 2000
          .Caption = "Hello"
          .Top = 1000
          .Left = 1000
       End With
    End Sub第三个例子添加一个非引用控件到 Controls 集合。然而要编程这样一个控件的事件,必须声明一个 VBControlExtender 类型的对象变量,并把由这个方法返回的引用设置到该对象。然后使用 ObjectEvent 事件编程该控件的事件。Option Explicit
    Dim ctlExtender As VBControlExtenderPrivate Sub Form_Load()
       Set ctlExtender = Controls.Add("Project1.UserControl1", "MyControl")
       With ctlExtender 
          .Visible = True
          .Top = 1000
          .Left = 1000
       End With
    End SubPrivate Sub extObj_ObjectEvent(Info As EventInfo)
       '使用 Select Case 编程该控件事件。
       Select Case Info.Name
       Case "UserName"
          '检查用户名值。
          MsgBox Info. EventParameters("UserName").Value
       '现在显示其他情况
       Case Else '未知事件
          '这里处理未知事件。
       End Select
    End Sub
      

  2.   

    还有一种方法是用控件数组的方式加载:
    如动态加载TEXT控件,在窗口中放置控件text1,将其index属性设为0即为控件数组中的第一个元素,将其可见属性设为False,动态加载时只需Load text1(1) Load text1(2)等即可
      

  3.   

    另需将动态加载控件的Visible属性设为True,注意不要重复加载相同下标值的同种控件
      

  4.   

    '先有form1上加一个text1 (0)Private Sub Form_Load()
        For i = 1 To 10
            Load Text1(i)
            Text1(i).Top = 400 * i + 200
            Text1(i).Left = 20
            Text1(i).Visible = True
        Next
    End Sub
      

  5.   

    Dim WithEvents ctlCommand As VB.CommandButtonPrivate Sub ctlCommand_Click()
        MsgBox "click"
    End SubPrivate Sub Form_Load()
    Set ctlCommand = Controls.Add("VB.CommandButton", "ctlCommand1", Me)
    '设置CommandButton的位置和尺寸ctlCommand.Top = 400 + 200
    ctlCommand.Left = 20'设置CommandButton的标题
    ctlCommand.Caption = "点击"
    '使CommandButton可见
    ctlCommand.Visible = TrueEnd Sub
      

  6.   

    先放置一个相同类型的控件,比如text1,将其索引设为0,然后可以load text1(i)
      

  7.   

    Dim Num As LongNum = Text1.UBound + 1
    Load Text1(Num)
    Text1(Num).Visible = TrueUnload Text1(Num) '用完了别忘了卸载