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

Asked

Viewed 394 times

0

Hello. I wonder if in VB.NET (Windows Forms) has how to make an event happen only during the time when the mouse button (LMB) is pressed.

For example, while the user holds 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 sending.

And also, if you can make it work in the background, in this case, not only within the program, but throughout the computer, using the press function for example, only that this would be more of a "hold" function, an example of code:

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

Thank you in advance.

  • Where do you want this code to be executed? In form? Has the events Mousedown and Mouseup for that purpose.

1 answer

0

The fastest solution that can be done is with the function GetAsyncKeyState 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 of the code.

Source of code 2.

Documentation of Getasynckeystate.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.