Mouse_click vise mouse_hold???

av8orfliboy

New member
Joined
Jul 25, 2007
Messages
4
Programming Experience
1-3
I want to click on a button and have it's affect repeated while the button is held. What is the right code to make this happen? Thanks!
 
Last edited:
Here is one way to do it.

VB.NET:
    Private i As Integer = 0
    Private IsMouseDown As Boolean = False
    Private Delegate Sub SetTextDelegate(ByVal value As Integer)

    Private Sub Form1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseDown
        IsMouseDown = True
        Dim ThrdWhileDown As New Threading.Thread(AddressOf WhileMouseDown)
        ThrdWhileDown.Start()
    End Sub

    Private Sub WhileMouseDown()
        While IsMouseDown
            i += 1
            SetText(i)
        End While
    End Sub

    Private Sub SetText(ByVal value As Integer)
        If Me.InvokeRequired Then
            Me.Invoke(New SetTextDelegate(AddressOf SetText), value)
        Else
            Me.Text = value.ToString
        End If
    End Sub
    Private Sub Form1_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseUp
        IsMouseDown = False
    End Sub

All I did here was create a new thread that executes while the boolean IsMouseDown is set to True. One thing you'll notice with this code is that the tight loop in the WhileMouseDown Sub Routine makes it difficult for the MouseUp event to fire.

Also with the above code you can disregard the SetText Sub Routine and the Delegate. I used them so that I could set properties in the form without cross threading.

A second way to do this is to create a timer and set the elapsed event. Mouse Down will enable the timer and Mouse Up will disable it. The only downside is that it will only run every time it elapsed, instead of the previous code.
 
Back
Top