Capture pressing a key in the background

Asked

Viewed 911 times

1

Hello, I would like to make my application detect when a certain key is pressed, but in the background, IE, there will be no form on display. I can detect the keys in the form with the code (Ctrl+L):

   If e.Control AndAlso e.KeyCode = Keys.L Then
       MessageBox.Show("Teste")
   End If

Thank you.

  • 1

    In c++ has a function called Getasynckeystate that serves to detect if a certain key is being pressed at that time in asynchronous mode. To use this function you would have to import a library that implements it and see if it works in a high-level language like Vb.net.

1 answer

1


We can use the function GetAsyncKeyState() from C++ as @viniciusafx mentioned in the comment of your question, for this we will create a reference for it.

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

Now let’s create the checker for when this key is pressed or not, for this we will create a Timer with break for 25ms (The shorter the interval, the better, but you can consume more processor in the execution. The longer the interval, the longer the user must press the key to call the action).

Private WithEvents Timer1 As New Timer With {
     .Interval = 25,  ' 25 ms
     .Enabled  = True ' ativa o timer
}

Now let’s create the code for the event Tick:

Private Sub Timer1_Click() Handles Timer1.Tick
    ...
End Sub

Now, within the above method, let’s declare three booleans, one to distinguish if the key Ctrl is being pressed, another to see if the key Shift is pressed, and then another to know if the key you want to press is being pressed:

Private ctrlKey As Boolean  = GetAsyncKeyState(Keys.ControlKey)
Private shiftKey As Boolean = GetAsyncKeyState(Keys.Shiftkey)
Private theKey As Boolean   = GetAsyncKeyState(Keys.K)

In the code below, will detect the combination Ctrl-Shift-K:

If ctrlKey = True And shiftKey = True And theKey = True Then
     ' código aqui...
End If

If you want a faster option, for the combination Ctrl + X:

If ctrlKey = True And (GetAsyncKeyState(Keys.X) = True) Then
     ' pressionou Ctrl + X
End If

Source of the code: http://www.dreamincode.net/forums/topic/94406-global-hotkey/

Browser other questions tagged

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