向运行时创建的控件添加处理程序

时间:2015-08-17 09:17:35

标签: vb6 runtime controls handler add

我在StackOverflow中找到了一些由#34; PaRiMaL RaJ"编写的vb.net代码。我想要相同的想法,但我必须将此代码转换为在VB6上工作。 你能帮我吗???

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    ' creating control
    Dim btn1 As Button = New Button()
    Dim btn2 As Button = New Button()

    btn1.Parent = Me
    btn1.Name = "btn1"
    btn1.Top = 10
    btn1.Text = "Btn1"

    btn2.Parent = Me
    btn2.Name = "btn2"
    btn2.Top = 50
    btn2.Text = "Btn2"

    'adding handler for click event
    AddHandler btn1.Click, AddressOf HandleDynamicButtonClick
    AddHandler btn2.Click, AddressOf HandleDynamicButtonClick


End Sub

Private Sub HandleDynamicButtonClick(ByVal sender As Object, ByVal e As EventArgs)
    Dim btn As Button = DirectCast(sender, Button)

    If btn.Name = "btn1" Then
        MessageBox.Show("Btn1 clicked")
    ElseIf btn.Name = "btn2" Then
        MessageBox.Show("Btn2 Clicked")
    End If

End Sub

1 个答案:

答案 0 :(得分:3)

最简单的方法是使用控件数组。在设计器中向表单添加一个按钮,并将其Index属性设置为0。如果您不希望它显示,您可以隐藏该按钮。

然后,当您想在运行时动态添加更多按钮时,只需使用Load语句。

例如,如果您的按钮名为Command1

Load Command1(1)                     ' Create a new button
Command1(1).Move 50, 50, 1500, 500   ' Set its size and position
Command1(1).Caption = "New Button"   ' Give it a caption
Command1(1).Visible = True           ' Make it visible

该按钮将使用与原始按钮相同的事件处理程序:

Private Sub Command1_Click(Index As Integer)

    ' Print the caption of the clicked button...
    Debug.Print Command1(Index).Caption

End Sub