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

Add handler to runtime-created control

我在 Whosebug 中发现了一些 vb.net 由 "PaRiMaL RaJ" 编写的代码。我想要同样的想法,但我必须将此代码转换为在 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

最简单的方法是使用控件数组。在设计器中向表单添加一个按钮,并将其 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