Can an Event Handler Remove Itself

RogerSchlueter-7899 1,236 Reputation points
2020-09-13T14:54:35.79+00:00

I want to limit a mouse event to be handled only once. I assign the event handler by responding to a Button Click:

Private Sub PreparePoint(sender As Object, e As RoutedEventArgs) Handles btnPoint.Click
    AddHandler Map.MouseLeftButtonDown, AddressOf FinishPoint
    .....
End Sub

and try to remove it as follows:

Private Sub FinishPoint(sender As Object, e As MouseButtonEventArgs)
    e.Handled = True
    RemoveHandler Map.MouseDown, AddressOf FinishPoint
    .....
End Sub

However, the event handler is not removed so I infer that my approach is not possible. Is that inference correct and, if so, how can I limit the mouse event to only one occurrence?

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,697 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Peter Fleischer (former MVP) 19,306 Reputation points
    2020-09-13T15:20:29.85+00:00

    Hi Roger,
    it works fine. Try following demo:

      <StackPanel>
        <Button x:Name="btn" Content="Click me"/>
      </StackPanel>
    

    And CodeBehind:

    Public Class Window1
    
      Private Sub Window_Loaded(sender As Object, e As RoutedEventArgs)
        AddHandler Me.btn.Click, AddressOf Btn_Click
      End Sub
    
      Private Sub Btn_Click(sender As Object, e As RoutedEventArgs)
        MessageBox.Show("Click Event")
        RemoveHandler Me.btn.Click, AddressOf Btn_Click
      End Sub
    
    End Class