Click here to Skip to main content
15,902,275 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Using VB.Net (Visual Studio Community 2017 version)

I'd like to use a picture of a button to change a counter value. I can do this once for each time the picture is clicked, but I want to have the counter value keep changing while the mouse is being held down on the picture and stop when the mouse is released. Also, I want the value to be incremented slowly, for example +1 for each 100 milliseconds or so while the mouse is down.

Any suggestions?

What I have tried:

Private Sub picButtonLeft_MouseDown(sender As Object, e As MouseEventArgs) Handles picButtonLeft.MouseDown

counter = counter + 1
Posted
Updated 4-May-18 9:23am

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


VB.NET
Imports System.Threading

Class MainWindow
    Dim cts As CancellationTokenSource

    Dim counter As Int32
    Private Async Sub PicButton_OnMouseDown(sender As Object, e As MouseEventArgs)
        ' Instantiate the CancellationTokenSource.
        cts = New CancellationTokenSource()
        Try
            While (True)
                'The CancellationTokenSource causes the loop to be broken
                'by throwing  an  OperationCanceledException
                'when the CancellationTokenSource.Cancel() method
                'is called in the mouseUp handler
                ' Asynchronous Delay 300millisecs
                'Ui thread is not blocked
                Await Task.Delay(300, cts.Token)
                counter = counter + 1
            End While

        Catch ex As OperationCanceledException
            cts = Nothing
            'Reset the counter here, if necessary
        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
 
Share this answer
 
v3
Use a Timer. Setup and start the timer in the MouseDown event and handle the Tick event of the Timer. There you'll increase your counter. Turn the Timer off in the MouseUp event.
 
Share this answer
 

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