在后台捕获键盘按键 [英] Capture a keyboard keypress in the background
问题描述
我有一个在后台运行的应用程序.每当用户按 F12 时,我都必须生成一些事件.所以我需要什么来捕捉按键.在我的应用程序中,如果任何时候用户按下 F10 一些事件将被执行.我不明白该怎么做?
I have a application that runs in the background. I have to generate some event whenever a user press F12 at anytime. So what I need that to capture a key-press. In my application, if any time a user press F10 some event will be performed. I don't understand how to do that?
有人知道怎么做吗?
N:B:这是一个winforms应用程序.它不需要关注我的表单.我的主窗口可能保留在系统托盘中,但它仍然必须捕获按键.
N:B: It is a winforms application. It doesn't need to have focus my form. My main window may remain in system tray but still it have to capture the keypress.
推荐答案
你想要的是一个全局热键.
在班级顶部导入所需的库:
Import needed libraries at the top of your class:
// DLL libraries used to manage hotkeys
[DllImport("user32.dll")]
public static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vlc);
[DllImport("user32.dll")]
public static extern bool UnregisterHotKey(IntPtr hWnd, int id);
在类中添加一个字段,作为代码中热键的引用:
Add a field in your class that will be a reference for the hotkey in your code:
const int MYACTION_HOTKEY_ID = 1;
注册热键(例如在 Windows 窗体的构造函数中):
Register the hotkey (in the constructor of your Windows Form for instance):
// Modifier keys codes: Alt = 1, Ctrl = 2, Shift = 4, Win = 8
// Compute the addition of each combination of the keys you want to be pressed
// ALT+CTRL = 1 + 2 = 3 , CTRL+SHIFT = 2 + 4 = 6...
RegisterHotKey(this.Handle, MYACTION_HOTKEY_ID, 6, (int) Keys.F12);
通过在类中添加以下方法来处理键入的键:
Handle the typed keys by adding the following method in your class:
protected override void WndProc(ref Message m) {
if (m.Msg == 0x0312 && m.WParam.ToInt32() == MYACTION_HOTKEY_ID) {
// My hotkey has been typed
// Do what you want here
// ...
}
base.WndProc(ref m);
}
这篇关于在后台捕获键盘按键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!