在后台捕获键盘按键

时间:2013-03-14 15:17:17

标签: c# winforms keypress

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

有人知道怎么做吗?

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

2 个答案:

答案 0 :(得分:35)

您想要的是全球热键

  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);
    }
    

答案 1 :(得分:9)

如果您在运行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。

相关问题