上一节讲了设计时创建控件,实际设计时候可以很方便地选择创建控件的事件代码,
本节讲一下不使用withevents,如何在运行时创建一个带有事件的控件。
主要用到 AddHandler 语句:
AddHandler event,AddressOf eventhandler
还是动态创建一个按钮:
Public Class Form2 Dim mybutton As Button Private Sub Form2_Load(sender As Object,e As EventArgs) Handles MyBase.Load mybutton = New Button mybutton.Size = New Size(200,70) mybutton.Location = New Point(100,100) mybutton.Text = "按钮" mybutton.Visible = True Me.Controls.Add(mybutton) AddHandler mybutton.Click,AddressOf buttonclick End Sub Private Sub buttonclick(sender As Object,e As EventArgs) MessageBox.Show("这是一个按钮") End Sub End Class
运行时如图:
我们可以通过参数 sender 来获得这个按钮(或其他动态创建的控件)的相关属性,
Private Sub buttonclick(sender As Object,e As EventArgs) 'MessageBox.Show("这是一个按钮") Dim thisButton As Button = CType(sender,Button) MessageBox.Show("我们按下了 " & thisButton.Text) End Sub
运行时如下: