我正在为我的视觉基础课程制作游戏。我有多个图片框,点击后会分别显示隐藏的图像。游戏的目的是找到匹配的图片(足够简单)。
在最简单的层面上,我有16个图片框。随着难度的增加,图片框的数量也会增加。
对于每个图片框,我目前有一个事件处理程序如下(默认由visual studio创建):
Private Sub pictureBox1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles pictureBox1.Click
在里面,我打算用它来改变图片框中的图像,如下所示:
pictureBox1.Image = (My.Resources.picture_name)
我想知道是否有办法让一个Sub处理所有按钮点击,并更改相应的图片框,而不是有16个单独的处理程序。例如:
Private Sub pictureBox1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles pictureBox1.Click, pictureBox2.Click, pictureBox3.Click, ... pictureBox16.Click
并执行以下操作:
' Change appropriate picture box
这就是它的样子(现在):
答案 0 :(得分:5)
要找出单击了哪个PictureBox,您只需查看sender变量即可。显然你必须将它从Object类型转换为PictureBox类型:
Dim ClickedBox As PictureBox
ClickedBox = CType(sender, PictureBox)
答案 1 :(得分:3)
我个人会做的是将你的公共EventHandler附加到你的PictureBox,给每个PictureBox一个Tag索引,除非你想对你的名字进行选择。然后你做这样的事情。
Private Sub PictureBox1_Click(sender As System.Object, e As System.EventArgs) Handles PictureBox1.Click, PictureBox2.Click, ...
Dim pb As PictureBox = CType(sender, PictureBox)
Select Case CInt(pb.Tag)
Case 0
pb.Image = My.Resources.PictureName1
Case 1
pb.Image = My.Resources.PictureName2
...
End Select
End Sub
答案 2 :(得分:0)
根据我所读到的,DirectCast优于CType
DirectCast可以与'With / End With'结合使用,如下所示:
Private Sub PictureBox1_Click(sender As System.Object, e As System.EventArgs) Handles PictureBox1.Click, PictureBox2.Click, ...
With DirectCast(sender, PictureBox)
Select Case CInt(.Tag)
Case 0
.Image = My.Resources.PictureName1
Case 1
.Image = My.Resources.PictureName2
...
End Select
End With
End Sub
我也尝试过以下内容,但这会导致奇怪的问题(控件消失)。
Using cbMe as CheckBox = DirectCast(sender, CheckBox)
cbMe.Checked = True
End Using
答案 3 :(得分:0)
迭代所有控件,例如
For Each ctr As Control In Me.Controls
If TypeOf ctr Is PictureBox Then
If ctr Is ActiveControl Then
' Do Something here
End If
End If
Next