Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
733 views
in Technique[技术] by (71.8m points)

vb.net - How to handle multiple click events with same Sub

I'm making a game for my visual basic course. I have multiple picture boxes that when clicked will reveal a hidden image individually. The point of the game is to find the matching pictures (simple enough).

On the easiest level, I have 16 picture boxes. The number of picture boxes increases as the difficulty increases.

For each picture box, I currently have an event handler as follows (default created by visual studio):

Private Sub pictureBox1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles pictureBox1.Click

Inside, I plan to use this to change the image in the picture box, as follows:

pictureBox1.Image = (My.Resources.picture_name)

I would like to know if there is a way to have one Sub handle ALL the button clicks, and change the appropriate picture box, instead of having 16 separate handlers. For example:

Private Sub pictureBox1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
     Handles pictureBox1.Click, pictureBox2.Click, pictureBox3.Click, ... pictureBox16.Click

And do the following:

' Change appropriate picture box

Here's what it looks like (for now):
enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To find out which PictureBox was clicked you just have to look at the sender variable. Obviously you have to convert it from the Object type to the PictureBox type:

Dim ClickedBox As PictureBox

ClickedBox = CType(sender, PictureBox)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...