0
Public Class Form1
    Dim i As Integer = 0
    Dim txt As New TextBox()
    Dim btn As New Button()

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        btn.Name = "btnMove"
        btn.Size = New Size(60, 20)
        btn.Location = New Point(220, 20)
        btn.Text = "move"
        btn.TextAlign = ContentAlignment.MiddleCenter
        Me.Controls.Add(btn)
        Me.BringToFront()
    End Sub

    Private Sub btnMove_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn.Click

    End Sub
End Class

这是我的代码,我想向 btn 按钮添加一个事件我希望我能清楚地说明我的问题并对我的英语不好表示抱歉

4

2 回答 2

1
Public Class Form2
    Dim btn As New Button
    Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        btn.Name = "btnMove"
        btn.Size = New Size(60, 20)
        btn.Location = New Point(220, 30)
        btn.Text = "Move"
        btn.TextAlign = ContentAlignment.MiddleCenter
        Me.Controls.Add(btn)
        Me.BringToFront()
        AddHandler btn.Click, AddressOf btnMove_click
    End Sub
    Private Sub btnMove_click(ByVal sender As Object, ByVal e As System.EventArgs)
        MsgBox("welcome to salfkjsadlkf")
    End Sub
End Class
于 2013-09-01T16:39:31.540 回答
1
   Private Sub btnMove_Click(...) Handles btn.Click

Handles关键字要求您使用WithEvents关键字声明生成事件的控件。使固定:

   Dim WithEvents btn As New Button()

另一种方法是使用 AddHandler 关键字显式订阅事件。在这种情况下,您可以省略Handles关键字并像这样编写它:

Private Sub Form1_Load(...) Handles MyBase.Load
   '' etc..
   AddHandler btn.Click, AddressOf btnMove_click
End Sub

使用设计器添加这些控件当然是最好的方法,它可以避免这样的小错误。

于 2013-09-01T16:43:13.830 回答