Search code examples
vb.neteventscontrols

VB.Net How to programmatically add a control and an event handler


I'm creating a game using the PictureBox control and adding a MouseDown event to handle reducing the "health" value of the PictureBox.

I would like to programmatically add a new control when the initial control loses all of it's health so that I can add variance to how the new PictureBox appears, but I do not know how to add an event handler to a programmatically created control.

Update: Thanks for the help! This is how my finished code works, if you would like to do the same.

Public Class Form1
    Private Sub NewBug()
        Dim pbBug As New PictureBox With {
        .Name = "pb",
        .Width = 100,
        .Height = 100,
        .Top = 75,
        .Left = 75,
        .SizeMode = PictureBoxSizeMode.Zoom,
        .Image = My.Resources.bug}
        Me.Controls.Add(pbBug)

        AddHandler pbBug.MouseDown, Sub(sender As Object, e As EventArgs)
                                    MessageBox.Show("Hello", "It Worked")
                                End Sub
    End Sub
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        NewBug()
    End Sub

Thanks, sunnyCr


Solution

  • Something isnt adding up. It would appear as though Dim MyButton As New Button() should be declared at Class scope, you should not have to declare WithEvents on local variables. Furthermore the MyButton_Click sub wouldnt compile if MyButton was Local to load routine. If it is declared at Class Scope then instead of Dim MyButton As New Button You would WithEvents MyButton As New Button If you want to keep it local then you could do something like this instead

    Dim MyButton As New Button With {
         .Name = "MyButton",
         .Top = 100,
         .Left = 100,
         .Image = My.Resources.SomeImage}
    
    Controls.Add(MyButton)
    
    AddHandler MyButton.Click, Sub(s As Object, ev As EventArgs)
                                   'Do stuff
                               End Sub
    

    which is generally how I do things as this, unless I intend to remove the handler, then I will create a Sub and use AddressOf such as how you are attempting to use it.