兩種方法:
目前成都創(chuàng)新互聯(lián)公司已為千余家的企業(yè)提供了網(wǎng)站建設(shè)、域名、網(wǎng)絡(luò)空間、網(wǎng)站托管、企業(yè)網(wǎng)站設(shè)計、蘭溪網(wǎng)站維護等服務(wù),公司將堅持客戶導(dǎo)向、應(yīng)用為本的策略,正道將秉承"和諧、參與、激情"的文化,與客戶和合作伙伴齊心協(xié)力一起成長,共同發(fā)展。
1. 用WithEvents聲明變量,這樣你就可以像對待拖上去的控件一樣操作:
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 語句:
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 語句:
'把圖片的聲明放在外面,類里面過程外面,而且要用As,不然等會兒沒法用
Dim myPicture As New System.Windows.Forms.PictureBox()
'動態(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 '綁定事件和過程
End Sub
'再來個事件,放在聲明的地方,就是類里面、過程外面
Private Event returnid(ByVal id As String) '這個事件可以傳遞值哦~
'普通的單擊事件
Private Sub mypic_Click()
RaiseEvent returnid(myPicture.Name)
End Sub
'會傳值的事件過程
Private Sub idReturned(ByVal id As String)
Dim bookInfo As New BookInfo
bookInfo.Show()
Me.Parent.Enabled = False
'用id變量做點什么吧
End Sub
如果要改事件的簽名(參數(shù)一類的)的話,得重寫控件。你可以這樣自己弄一個事件。
常見事件有鼠的標(biāo)單擊、雙擊、移動;
有鍵盤的鍵按下、鍵松開、按鍵;
有窗體加載、窗體卸載等等。
動態(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
處理事件的過程:
Private?Sub?mypic_Click()?'ByVal?id?As?String
Dim?bookInfo?As?New?BookInfo
bookInfo.Show()
Me.Parent.Enabled?=?False
Option Explicit
'添加事件
Private WithEvents cmd As CommandButton
Private Sub Form_Load()
Set cmd = Controls.Add("VB.CommandButton", "cmd")
cmd.Visible = True
End Sub