兩種方法:
創(chuàng)新互聯(lián)建站是一家專業(yè)提供凌源企業(yè)網(wǎng)站建設(shè),專注與成都網(wǎng)站設(shè)計(jì)、做網(wǎng)站、成都外貿(mào)網(wǎng)站建設(shè)公司、HTML5、小程序制作等業(yè)務(wù)。10年已為凌源眾多企業(yè)、政府機(jī)構(gòu)等服務(wù)。創(chuàng)新互聯(lián)專業(yè)網(wǎng)站制作公司優(yōu)惠進(jìn)行中。
1. 用WithEvents聲明變量,這樣你就可以像對(duì)待拖上去的控件一樣操作:
Public?Class?Form3
WithEvents?btn?As?New?Button
Private?Sub?Form3_Load(sender?As?Object,?e?As?EventArgs)?Handles?Me.Load
Controls.Add(btn)
End?Sub
Private?Sub?btn_Click(sender?As?Object,?e?As?EventArgs)?Handles?btn.Click
MsgBox(Now)
End?Sub
End?Class
2. 使用AddHandler 語(yǔ)句:
Public?Class?Form3
Private?Sub?Form3_Load(sender?As?Object,?e?As?EventArgs)?Handles?Me.Load
Dim?btn?As?New?Button
AddHandler?btn.Click,?AddressOf?btn_Click
Controls.Add(btn)
End?Sub
Private?Sub?btn_Click(sender?As?Object,?e?As?EventArgs)
MsgBox(Now)
End?Sub
End?Class
WithEvents (Visual Basic):
AddHandler 語(yǔ)句:
'把圖片的聲明放在外面,類里面過(guò)程外面,而且要用As,不然等會(huì)兒沒法用
Dim myPicture As New System.Windows.Forms.PictureBox()
'動(dòng)態(tài)生成的控件,加一行
Private Sub UserControl1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Me.Panel3.Controls.Add(myPicture)
myPicture.Size =New System.Drawing.Size(115, 160)
myPicture.TabStop =False
myPicture.Name ="p"
myPicture.Cursor = Cursors.Hand
AddHandler myPicture.Click, AddressOf mypic_Click '添加事件
AddHandler returnid, AddressOf idReturned '綁定事件和過(guò)程
End Sub
'再來(lái)個(gè)事件,放在聲明的地方,就是類里面、過(guò)程外面
Private Event returnid(ByVal id As String) '這個(gè)事件可以傳遞值哦~
'普通的單擊事件
Private Sub mypic_Click()
RaiseEvent returnid(myPicture.Name)
End Sub
'會(huì)傳值的事件過(guò)程
Private Sub idReturned(ByVal id As String)
Dim bookInfo As New BookInfo
bookInfo.Show()
Me.Parent.Enabled = False
'用id變量做點(diǎn)什么吧
End Sub
如果要改事件的簽名(參數(shù)一類的)的話,得重寫控件。你可以這樣自己弄一個(gè)事件。
動(dòng)態(tài)生成的控件:
Private?Sub?UserControl1_Load(sender?As?System.Object,?e?As?System.EventArgs)?Handles?MyBase.Load
Dim?myPicture?=?New?System.Windows.Forms.PictureBox()
Me.Panel3.Controls.Add(myPicture)
myPicture.Size?=?New?System.Drawing.Size(115,?160)
myPicture.TabStop?=?False
myPicture.Name?=?"p"?
myPicture.Cursor?=?Cursors.Hand
AddHandler?myPicture.Click,?AddressOf?mypic_Click?'添加事件
End?Sub
處理事件的過(guò)程:
Private?Sub?mypic_Click()?'ByVal?id?As?String
Dim?bookInfo?As?New?BookInfo
bookInfo.Show()
Me.Parent.Enabled?=?False