How to handle multiple click events with the same Sub

I am making a game for my visual basic course. I have several boxes for images that, when clicked, will show the hidden image separately. The goal of the game is to find matching photos (fairly simple).

At the simplest level, I have 16 image boxes. The number of images increases with increasing complexity.

For each image window, I currently have an event handler (created by visual studio by default):

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

Internally, I plan to use this to change the image in the image window, as follows:

 pictureBox1.Image = (My.Resources.picture_name) 

I would like to know if there is a way for one auxiliary ALL descriptor to click a button and change the corresponding image block instead of 16 separate handlers. For instance:

 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

+4
source share
4 answers

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

 Dim ClickedBox As PictureBox ClickedBox = CType(sender, PictureBox) 
+5
source

Personally, I would like to add your general EventHandler to your PictureBox, give each PictureBox Tag for the index, if only you want to make your choice in the name. Then you do something like this.

 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
source

According to what I read, DirectCast is preferable to CType

DirectCast can be combined with 'With / End With', as shown below:

 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 

I also tried the following, but this causes strange problems (the controls disappear).

 Using cbMe as CheckBox = DirectCast(sender, CheckBox) cbMe.Checked = True End Using 
0
source

Iterate through all controls e.g.

  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 
0
source

Source: https://habr.com/ru/post/1445221/


All Articles