Listen to key press when the program is in the bac

2019-01-08 02:39发布

问题:

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.

回答1:

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 KeyDownBit As Integer = &H8000

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

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(Keys.LWin) AndAlso GetAsyncKeyState(Keys.O)
End While

This will stop your code from executing more than once while you hold the keys down.

When using this in a Console Application just replace every System.Windows.Forms.Keys and Keys with ConsoleKey, and replace LWin with LeftWindows.