我知道如何使用加速表在我的应用程序中设置热键。但是我如何在全球范围内得到一个热键呢?
也就是说,我的应用程序正在运行,但最小化了。但我仍然希望它能检测和处理一个热键。
发布于 2022-06-19 13:02:25
如果您需要一个系统范围的热键,那么您应该使用RegisterHotKey,传入窗口处理程序负责处理事件的窗口句柄。在应用程序级别,这通常是CFrameWnd/CFrameWndEx-derived窗口实现。
一旦注册了热键,接收窗口就可以在其自定义CWnd::OnHotKey覆盖中观察事件。确保将ON_WM_HOTKEY()消息处理程序添加到接收窗口实现的消息映射中。
对于标准的、默认生成的SDI/MDI应用程序,您需要应用以下更改。
MainFrm.h:
class CMainFrame : public CFrameWnd
{
// ...
private:
// Hot key handler routine
afx_msg void OnHotKey(UINT nHotKeyId, UINT nKey1, UINT nKey2);
};MainFrm.cpp:
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实现:
void CMainFrame::OnHotKey(UINT nHotKeyId, UINT nKey1, UINT nKey2) {
if (this->IsIconic()) {
this->ShowWindow(SW_RESTORE);
}
this->SetForegroundWindow();
}没有闪烁的任务栏按钮,一切只是工作的预期。
https://stackoverflow.com/questions/72676476
复制相似问题