Click here to Skip to main content
15,881,281 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I need to make an event in a custom control that has the ability to be canceled by the forms event handler. How does one do this seeing as the event fires internally before externally?
Posted

You can copy the KeyPress event.

The KeyPress event when fired from code passes a KeyEventArgs object. This object has a property called Handled.

So, create your own EventArgs class and add a property called Handled that is a boolean value. When you initialize your custom class, you set Handled to false. Then, the user has the option to set handled to true and you check that value after you raise the event.

If Handled equals true, you don't do anything further. If not, you process it as normal.
 
Share this answer
 
The custom event arguments with a cancel property
Public Class MyEventArgs
    Inherits EventArgs
    Private CancelValue As Boolean = False
    Sub New()
        MyBase.New()
    End Sub
    Public Property Cancel As Boolean
        Get
            Return CancelValue
        End Get
        Set(value As Boolean)
            CancelValue = value
        End Set
    End Property
End Class


When you use the event in the class that raises the event you can raise the event and wait before you execute code. example:

Public Class MyObject
    Public Event MyEvent(e As MyEventArgs)

    Public Sub MySub()
        Dim MyEvent1 As New MyEventArgs()

        RaiseEvent MyEvent(MyEvent1)

        If MyEvent.Cancel = False Then
            'Do the thing
        Else
            'Don't do the thing
        End If
    End Sub
End Class


When the event gets raised by the object simply set e.cancel = True like the following:

Private Sub MyObject1_MyEvent(e As MyEventArgs) Handles MyObject1.MyEvent

    If SomethingHappens Then
        e.cancel = True
    End If

End Sub
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900