add on click event to picturebox vb.net

2019-02-23 17:12发布

问题:

I have a flowLayoutPanel which I am programatically adding new panelLayouts to. Each panelLayout has a pictureBox within it. It's all working nicely, but I need to detect when that picture box is clicked on. How do I add an event to the picture? I seem to only be able to find c# examples....

my code to add the image is as follows...

        ' add pic to the little panel container
        Dim pic As New PictureBox()
        pic.Size = New Size(cover_width, cover_height)
        pic.Location = New Point(10, 0)
        pic.Image = Image.FromFile("c:/test.jpg")
        panel.Controls.Add(pic)

        'add pic and other labels (hidden in this example) to the big panel flow
        albumFlow.Controls.Add(panel)

So I assume somewhere when I'm creating the image I add an onclick event. I need to get the index for it also if that is possible! Thanks for any help!

回答1:

Use the AddHandler statement to subscribe to the Click event:

    AddHandler pic.Click, AddressOf pic_Click

The sender argument of the pic_Click() method gives you a reference to the picture box back:

Private Sub pic_Click(ByVal sender As Object, ByVal e As EventArgs)
    Dim pic As PictureBox = DirectCast(sender, PictureBox)
    ' etc...
End Sub

If you need additional info about the specific control, like an index, then you can use the Tag property.



回答2:

Substitute PictureBox1 with the name of your control.

Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.Click
    'executes when PictureBox1 is clicked
End Sub