27

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

有谁知道怎么做?

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

4

2 回答 2

49

你想要的是一个全局热键

  1. 在类的顶部导入所需的库:

    // 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);
    }
    
于 2013-03-14T15:22:50.537 回答
17

如果您在运行 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 fsModifers, int vlc);
    
        [DllImport("user32.dll")]
        public static extern bool UnregisterHotKey(IntPtr hWnd, int id);
    }
    
  3. 您不需要添加 user32.dll 作为对项目的引用。WinForms 总是自动加载这个 dll。

于 2015-01-08T10:50:12.047 回答