noidea noidea - 5 months ago 27
Vb.net Question

Disable picturebox_click event on vb.net

I'm using a click event on a picture box, that can only be enabled after some actions.

Private Sub PictureBox_Click_1(sender As Object, e As EventArgs) Handles PictureBox.Click


But i want to disable that click without using
picturebox.enabled=false
cause it changes the original colour to grey.

How can i do that ? Thank you!

Answer

There are two possibilities.

  1. You use a boolean value indicating that you don't want to run the logic in the event handler.

    Here is an example:

    Private _usePictureBoxEvent as Boolean = True
    
    Private Sub PictureBox_Click_1(sender As Object, e As EventArgs) Handles PictureBox.Click
        If _usePictureBoxEvent Then
            'Do your event stuff here
        End If
    End Sub
    

    To deactivate the event handling:

    _usePictureBoxEvent = False 'the event will still be activated but we'll do nothing
    
  2. Dynamically subscribe to the event: AddHandler and RemoveHandler

    Here's an example:

    Public Sub New()
        'VS calls this, don't touch
        InitializeComponents()
    
        'We add a listener to this event
        AddHandler Me.PictureBox.Click, AddressOf PictureBox_Click_1
    
        'Other stuff
    End Sub
    
    Private Sub PictureBox_Click_1(sender As Object, e As EventArgs) 'No more Handles clause
        'Do your event stuff
    
    End Sub
    

    And to stop the event from triggering:

    'Anywhere in your code
    RemoveHandler Me.PictureBox.Click, AddressOf PictureBox_Click_1