我有一个在后台运行的应用程序。每当用户随时按下 F12 键时,我必须生成一些事件。所以我需要捕获按键操作。在我的应用程序中,如果用户在任何时候按下 F10,将执行某些事件。我不知道该怎么做?
有人知道如何做吗?
注: 这是一个WinForms应用程序。它不需要关注我的窗体。我的主窗口可能仍然在系统托盘中,但它仍然必须捕获按键操作。
有人知道如何做吗?
注: 这是一个WinForms应用程序。它不需要关注我的窗体。我的主窗口可能仍然在系统托盘中,但它仍然必须捕获按键操作。
您需要的是一个全局热键。
在类的顶部导入所需的库:
// 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);
在你的类中添加一个字段,用于在代码中引用快捷键:const int MYACTION_HOTKEY_ID = 1;
在您的 Windows 表单构造函数中注册热键:
// 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);
在您的类中添加以下方法来处理键入的按键: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);
}
如果您在运行Otiel的解决方案时遇到问题:
您需要包含:
using System.Runtime.InteropServices; //required for dll import
像我这样的新手还有一个疑问:“班级顶尖”真的意味着你所在班级的顶尖,而不是命名空间或构造函数之类的意思吗?
public partial class Form1 : Form
{
[DllImport("user32.dll")]
public static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifers, int vlc);
[DllImport("user32.dll")]
public static extern bool UnregisterHotKey(IntPtr hWnd, int id);
}
您无需将user32.dll添加为项目的引用。WinForms始终会自动加载此dll。