Richard Olsen Sandberg Richard Olsen Sandberg - 4 months ago 9
Vb.net Question

Listen to key press when the program is in the background

I am currently working with a program which is supposed to run in the background but also check if "mod + o" is pressed then do something. But I cannot figure out how a vb.net program can listen to key presses when the program is not Selected / Opened.

Answer

You can use P/Invocation to be able to use WinAPI's GetAsyncKeyState() function, then check that in a timer.

<DllImport("user32.dll")> _
Public Shared Function GetAsyncKeyState(ByVal vKey As System.Windows.Forms.Keys) As Short
End Function

Const KeyDown As Integer = &H8000

Private Sub Timer1_Tick(sender As Object, e As System.EventArgs) Handles Timer1.Tick
    If (GetAsyncKeyState(Keys.O) And KeyDown) = KeyDown Then
        'Do whatever you want when 'O' is held down.
    End If
End Sub

I cannot seem to find what the Mod key is, so you can do this in your form (when it has focus):

Private Sub Form1_KeyDown(sender As Object, e As KeyEventArgs) Handles Form1.KeyDown
    MessageBox.Show(Convert.ToInt32(e.KeyCode))
End Sub

Press the 'Mod' button ONLY, then take the number from the message box that popups and put it in the timer:

If (GetAsyncKeyState(<put number here>) And KeyDown) = KeyDown AndAlso (GetAsyncKeyState(Keys.O) And KeyDown) = KeyDown Then
        'Do whatever you want when 'Mod + O' is held down.
End If

EDIT:

To make the code only execute one time per key press, you can add a little While-loop to run until either of the buttons are released (add it inside your If-statement):

While GetAsyncKeyState(ConsoleKey.LeftWindows) AndAlso GetAsyncKeyState(ConsoleKey.O)
End While

This will stop your code from executing many times when you only press the combination once.

Comments