Try using the Async Await Task-based Pattern
. Trap the PreviewMouseLeftButtonDown
and PreviewMouseLeftButtonUp
events. I would not use MouseLeftButtonDown
as it is handled by the Button Click event and will not be trapped by your method. I have just noticed that your button is not a button but a Picture Box but the idea is exactly the same
Imports System.Threading
Class MainWindow
Dim cts As CancellationTokenSource
Dim counter As Int32
Private Async Sub PicButton_OnMouseDown(sender As Object, e As MouseEventArgs)
cts = New CancellationTokenSource()
Try
While (True)
Await Task.Delay(300, cts.Token)
counter = counter + 1
End While
Catch ex As OperationCanceledException
cts = Nothing
End Try
End Sub
Private Sub PicButton_OnMouseUp(sender As Object, e As MouseEventArgs)
If cts IsNot Nothing Then
cts.Cancel()
End If
End Sub