在后台捕获键盘按键

我有一个在后台运行的应用程序。 每当用户随时按F12时 ,我都必须生成一些事件。 所以我需要这样才能捕获按键。 在我的应用程序中,如果用户按任何时间F10,将执行某些事件。 我不明白该怎么做?

有谁知道怎么做?

N:B:这是一个winforms应用程序。 它不需要关注我的forms。 我的主窗口可能仍保留在系统托盘中,但仍然需要捕获按键。

你想要的是全球热门

  1. 在您的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); 
  2. 在您的类中添加一个字段,该字段将成为代码中热键的引用:

     const int MYACTION_HOTKEY_ID = 1; 
  3. 注册热键(例如,在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); 
  4. 通过在类中添加以下方法来处理键入的键:

     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的解决方案时遇到问题:

  1. 你需要包括:

     using System.Runtime.InteropServices; //required for dll import 
  2. 对于像我这样的新手的另一个疑问:“类的顶级”真的意味着像这样的顶级(不是命名空间或构造函数):

     public partial class Form1 : Form { [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); 
  3. 您不需要添加user32.dll作为项目的引用。 WinForms总是自动加载此dll。