首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在MFC应用程序中设置全局热键的正确方法是什么?

问在MFC应用程序中设置全局热键的正确方法是什么?
EN

Stack Overflow用户
提问于 2022-06-19 11:26:34
回答 1查看 92关注 0票数 1

我知道如何使用加速表在我的应用程序中设置热键。但是我如何在全球范围内得到一个热键呢?

也就是说,我的应用程序正在运行,但最小化了。但我仍然希望它能检测和处理一个热键。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-06-19 13:02:25

如果您需要一个系统范围的热键,那么您应该使用RegisterHotKey,传入窗口处理程序负责处理事件的窗口句柄。在应用程序级别,这通常是CFrameWnd/CFrameWndEx-derived窗口实现。

一旦注册了热键,接收窗口就可以在其自定义CWnd::OnHotKey覆盖中观察事件。确保将ON_WM_HOTKEY()消息处理程序添加到接收窗口实现的消息映射中。

对于标准的、默认生成的SDI/MDI应用程序,您需要应用以下更改。

MainFrm.h:

代码语言:javascript
复制
class CMainFrame : public CFrameWnd
{
    // ...
private:
    // Hot key handler routine
    afx_msg void OnHotKey(UINT nHotKeyId, UINT nKey1, UINT nKey2);
};

MainFrm.cpp:

代码语言:javascript
复制
BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
    // ...

    // Make sure that WM_HOTKEY messages are routed to this window
    ON_WM_HOTKEY()
END_MESSAGE_MAP()

// Hot key ID; can be any value in the range 0x0000 through 0xBFFF
// Allows the application to identify this hot key in case there is more than one
constexpr int MyHotKeyId = 42;

int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct) {
    // ...

    // Register a global system-wide hot key (Ctrl+Shift+Alt+I)
    if (!::RegisterHotKey(this->m_hWnd, MyHotKeyId,
                          MOD_ALT | MOD_SHIFT | MOD_CONTROL | MOD_NOREPEAT,
                          'I')) {
        auto const ec = ::GetLastError();
        auto const err_msg = std::format(L"RegisterHotKey failed (error: {})\n",
                                         ec);
        ::OutputDebugStringW(err_msg.c_str());

        // Probably a good idea to handle failure more gracefully than this:
        return -1;
    }

    return 0;
}

void CMainFrame::OnHotKey(UINT nHotKeyId, UINT nKey1, UINT nKey2) {
    // Handle hot key; nHotKeyId is MyHotKeyId in this case
}

注意,接收WM_HOTKEY消息会授予接收线程前台激活权限。如果您希望应用程序在收到注册的热键后到达前台,可以使用以下OnHotKey实现:

代码语言:javascript
复制
void CMainFrame::OnHotKey(UINT nHotKeyId, UINT nKey1, UINT nKey2) {
    if (this->IsIconic()) {
        this->ShowWindow(SW_RESTORE);
    }
    this->SetForegroundWindow();
}

没有闪烁的任务栏按钮,一切只是工作的预期。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72676476

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档