Capturing a keystroke in the background

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 in view. I can make the detection of 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.

    
asked by anonymous 18.02.2017 / 02:54

1 answer

1

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

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

Now we will create the checker for when this key is pressed or not, so we will create a Timer with interval for 25ms (the lower the interval, the better, however, it may consume more processor in the execution. interval, the longer the user should 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 Tick event:

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

Now, within the above method, we will declare three Booleans, one to distinguish whether the Ctrl key is being pressed, another to see if the Shift key is pressed, and then another to see if the key you want to be pressed 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, it 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 Ctrl + X combination:

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

Source code: link

    
20.02.2017 / 02:38