如果您使用的是Handles
關鍵字,這是默認,處理典型方式來自控件的事件,可以向Handles
子句添加多個事件名稱,例如:
Private Sub OnClick(sender As Object, e As EventArgs) Handles PictureBox1.Click, PictureBox2.Click, PictureBox3.Click
' Handles click events from PictureBox1, PictureBox2, and PictureBox3
End Sub
或者,您也可以手動聲明事件處理方法沒有Handles
條款,然後將其連接到事件自己,就像這樣:
Private Sub OnClick(sender As Object, e As EventArgs)
' ...
End Sub
' ...
AddHandler PictureBox1.Click, AddressOf OnClick
AddHandler PictureBox2.Click, AddressOf OnClick
AddHandler PictureBox3.Click, AddressOf OnClick
或者,如果你有圖片框控件列表,您可以添加事件處理程序在一個循環中,像這樣:
Dim myPictureBoxes() As PictureBox = {PictureBox1, PictureBox2, PictureBox3}
For Each i As PictureBox in myPictureBoxes
AddHandler i.Click, AddressOf OnClick
Next
或者,你可以從你的窗體的Controls
集合按名稱訪問這些:
For i As Integer = 1 to 30
Dim c As Control = Me.Controls("PictureBox" & i.ToString())
AddHandler c.Click, AddressOf OnClick
Next
但請記住,如果您手動調用AddHandler
,則還需要調用RemoveHandler
以稍後分離事件處理程序。儘管如此,從表面上看,似乎很奇怪有這麼多的圖片框。您可能需要考慮在單個控件中自定義繪製內容,或者考慮在運行時動態加載控件。
[如何處理具有相同Sub的多個點擊事件]的可能重複(http://stackoverflow.com/questions/13323397/how-to-handle-multiple-click-events-with-same-sub) – Plutonix 2014-10-28 15:03:04