当程序在后台时听按键 [英] Listen to key press when the program is in the background
问题描述
我目前正在使用一个应该在后台运行的程序,但还要检查是否按下了mod + o",然后执行某些操作.但是我无法弄清楚当程序不是 Selected/Opened 时,vb.net 程序如何侦听按键.
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.
推荐答案
您可以使用 P/Invocation 来使用 WinAPI 的 GetAsyncKeyState() 函数,然后在计时器中检查.
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
<小时>
要使代码每次按键仅执行一次,您可以添加一个小 While
循环以运行直到释放任一按钮(将其添加内部你的 If
语句):
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.
在控制台应用程序中使用它时,只需将每个 System.Windows.Forms.Keys
和 Keys
替换为 ConsoleKey
,然后替换 LWin
和 LeftWindows
.
When using this in a Console Application just replace every System.Windows.Forms.Keys
and Keys
with ConsoleKey
, and replace LWin
with LeftWindows
.
这篇关于当程序在后台时听按键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!