qt实现全局热键(win下)
文章目录
1. 注册热键
BOOL RegisterHotKey(
HWND hWnd,
int id,
UINT fsModifiers,
UINT vk
);
//https://docs.microsoft.com/en-us/previous-versions/aa922958(v=msdn.10)
2. 实现QAbstractNativeEventFilter,重载nativeEventFilter,在此方法中处理WM_HOTKEY消息
#include <windows.h>
class WinEventFilter:public QAbstractNativeEventFilter{
public:
bool nativeEventFilter(const QByteArray &eventType, void *message, long *result){
if(eventType == "windows_generic_MSG") {
MSG *msg = static_cast<MSG *>(message);
if(msg->message == WM_HOTKEY) {
//处理热键消息
UINT fuModifiers = (UINT) LOWORD(msg->lParam);
UINT uVirtKey = (UINT) HIWORD(msg->lParam);
//虚拟键码查询 https://docs.microsoft.com/zh-cn/windows/win32/inputdev/virtual-key-codes
//消息各字段含义 https://docs.microsoft.com/en-us/previous-versions/aa931321(v=msdn.10)?redirectedfrom=MSDN
}
}
return false;//返回false消息继续向上传递,返回true消息不继续向上传递
}
};
3. QApplication中安装NativeEventFilter
#include <windows.h>
QApplication a(argc, args);
a.installNativeEventFilter(new WinEventFilter);
0. 流程解析
调用win32api RegisterHotKey后,注册热键。按下注册过的热键就会产生WM_HOTKEY消息。
重载QAbstractNativeEventFilter处理WM_HOTKEY消息。
QApplication安装此NativeEventFilter即可全局监听消息