全局键盘挂钩 (C#)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/824229/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 03:04:10  来源:igfitidea点击:

Global Keyboard Hooks (C#)

c#windowshotkeysglobal-hotkey

提问by

Possible Duplicate:
Global keyboard capture in C# application

可能的重复:
C# 应用程序中的全局键盘捕获

Can anyone help me setup a global keyboard hook for my application?

谁能帮我为我的应用程序设置一个全局键盘钩子?

I want to set hotkeys (such as Ctrl+S) that can be used when not focused on the actual form.

我想设置在不关注实际表单时可以使用的热键(例如Ctrl+ S)。

回答by Tim Robinson

Paul's post links to two answers, one telling you how to implement a hook, and another telling you to call RegisterHotKey. You shouldn't need to install a hook for something as simple as a Ctrl+S hotkey, so call RegisterHotKeyinstead.

Paul 的帖子链接到两个答案,一个告诉您如何实现钩子,另一个告诉您调用 RegisterHotKey。您不需要为像 Ctrl+S 热键这样简单的东西安装钩子,因此请改为调用RegisterHotKey

回答by Tim Robinson

Or you can use C#'s MessageFilter. It should work while any control/form from your application's process has focus.

或者您可以使用 C# 的 MessageFilter。当您的应用程序流程中的任何控件/表单具有焦点时,它应该可以工作。

Sample Code:

示例代码:

class KeyboardMessageFilter : IMessageFilter
{
    public bool PreFilterMessage(ref Message m)
    {
        if (m.Msg == ((int)Helper.WindowsMessages.WM_KEYDOWN))
        {
            switch ((int)m.WParam)
            {
                case (int)Keys.Escape:
                    // Do Something
                    return true;
                case (int)Keys.Right:
                    // Do Something
                    return true;
                case (int)Keys.Left:
                    // Do Something
                    return true;
            }
        }

        return false;
    }
}

And than simply add a new MessageFilter to your Application:

而不是简单地向您的应用程序添加一个新的 MessageFilter:

Application.AddMessageFilter(new KeyboardMessageFilter());