How to make an event run only when the mouse is pressed

0

Hello. I would like to know if VB.NET (Windows forms) has how to make an event happen only during the time that the mouse button (LMB) is pressed.

For example, as long as the user holds down the mouse button, the "W" key will be sent several times. And as soon as he releases the mouse button, the "W" key will stop being sent.

And also, if you have to do this work in the background, in this case, not only within the program, but throughout the computer, using the press function for example, only this would be more a "hold" function, code example:

If Held.Keys.LMB = True
    SendKeys.Send("W")
End If

Thank you in advance.

    
asked by anonymous 08.07.2018 / 00:48

1 answer

0

The fastest solution that can be done is with the GetAsyncKeyState function using a Timer.

Option Explicit

Private Declare Function GetAsyncKeyState Lib "user32" (ByVal vKey As Long) As Integer

' Esse valor é dado em milissegundos, define o tempo
' que o timer irá verificar se o botão do mouse está sendo pressionado
' e se estiver, irá chamar o evento
' Obs.: valores mais baixos influenciam numa perda de performance drástica
Public Const TempoResposta As Integer = 500

Public WithEvents Timer1 As New Timer

Private Sub Form_Load()
    Timer1.Interval = TempoResposta
    Timer1.Enabled = True
End Sub

Private Sub Timer1_Timer() Handles Timer1.Tick
    ' Botão esquerdo do mouse
    If GetAsyncKeyState(1) = 0 Then
         SendKeys.Send("W")
    End If

'    ' Botão direito do mouse
'    If GetAsyncKeyState(2) = 0 Then
'        ' está sendo pressionado
'    Else
'        ' foi soltado
'    End If
End Sub

In the code, a timer with events has already been declared. You can use one that has already been used in Designer, just replace the names.

Source Code

Source Code 2.

GetAsyncKeyState documentation.

    
29.07.2018 / 00:06