0

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!

noidea
  • 184
  • 5
  • 22

2 Answers2

1

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
    
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Martin Verjans
  • 4,675
  • 1
  • 21
  • 48
0

If you are using a static event handler ( Handles [...] ) is a bit harder to remove it.

The easiest and cleanest solution would be to have a boolean and check its value on the event (and changing it where you need to allow/disallow it).

Or change it to a non-static handler: AddHandler/RemoveHandler.

Other solutions would imply inheriting the PictureBox and overriding the OnClick method.

Stefano d'Antonio
  • 5,874
  • 3
  • 32
  • 45