程序在后台时听按键 [英] Listen to key press when the program is in the background

查看:18
本文介绍了程序在后台时听按键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用一个应该在后台运行的程序,但还要检查是否按下了mod + o"然后做一些事情.但我无法弄清楚 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-循环来运行,直到任一按钮被释放(将其添加inside您的 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.KeysKeys 替换为 ConsoleKey,然后替换 >LWinLeftWindows.

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

这篇关于程序在后台时听按键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆