全局键盘挂钩 (C#)

发布于 2024-07-19 08:08:28 字数 280 浏览 5 评论 0原文

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

任何人都可以帮我设置全局键盘挂钩我的应用程序?

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

Possible Duplicate:
Global keyboard capture in C# application

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

只有一腔孤勇 2024-07-26 08:08:28

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

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 RegisterHotKey instead.

雨夜星沙 2024-07-26 08:08:28

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

示例代码:

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

不仅仅是向您的应用程序添加一个新的 MessageFilter:

Application.AddMessageFilter(new KeyboardMessageFilter());

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

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:

Application.AddMessageFilter(new KeyboardMessageFilter());
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文