在后台捕获键盘按键

Imo*_*zid 19 c# keypress winforms

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

有谁知道怎么做?

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

Oti*_*iel 36

你想要的是全球热门.

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

    const int MYACTION_HOTKEY_ID = 1;
    
    Run Code Online (Sandbox Code Playgroud)
  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);
    
    Run Code Online (Sandbox Code Playgroud)
  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);
    }
    
    Run Code Online (Sandbox Code Playgroud)

  • 顺便说一句,我不是全局热键的忠实粉丝 - 我认为它们可能是“危险的”。如果两个应用程序注册了相同的密钥怎么办?除非非常小心地处理,否则它可能会产生意想不到的后果。即使你小心处理你的应用程序,也没有什么说其他应用程序做同样的事情。有点像成为一名出色的司机,但不得不担心路上的其他司机。 (2认同)
  • 我正在尝试在 windows 应用程序的 main.cs 中注册热键,因为我不希望它具有任何形式,但是 this.Handle 在这种情况下不存在。任何想法如何获得它? (2认同)
  • 它如何在控制台应用程序中使用?我没有这个。处理 (2认同)

bar*_*tek 9

如果您在运行Otiel的解决方案时遇到问题:

  1. 你需要包括:

    using System.Runtime.InteropServices; //required for dll import
    
    Run Code Online (Sandbox Code Playgroud)
  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);
    
    Run Code Online (Sandbox Code Playgroud)
  3. 您不需要添加user32.dll作为项目的引用.WinForms总是自动加载此DLL.