键盘事件消息发送
- QApplication::sendEvent(QObject* pObj,QEvent* event);
特点:利用QEvent类实现消息的发送,不需要调用WindowAPI;
问题,只能在Qt程序内部工作,不能跨程序响应,同时需要重写QKeyEvent函数完成最终的结果执行。只适合用于程序内嵌的简单事件响应。
QKeyEvent* keyEve = new QKeyEvent(QEvent::KeyPress,Qt::Key_Up,Qt::NoModifier,"");
QApplication::sendEvent(this,keyEve);
- Windows 消息 PostMessage(),SendMessage()
特点:调用Windows的消息工具,实现系统级消息响应,验证效果较好。相对而言,需要调用Win API,并需要创建windows 消息,较为复杂一些。
sendMessage 与postMessage参数一致,执行时,Send会等待消息执行完成后再返回,所以返回值为LRESULT,而postMessage只判断消息是否成功发送,返回一个bool变量。
SendMessage windows Docs
LRESULT SendMessage(
HWND hWnd,
UINT Msg,
WPARAM wParam,
LPARAM lParam
);
PostMessage windows Docs
BOOL PostMessageA(
HWND hWnd,
UINT Msg,
WPARAM wParam,
LPARAM lParam
);
使用示例
bool ret = PostMessage(HWND_BROADCAST,WM_CHAR,65,1);
// 模拟A键
参数详解:
- hWnd
Type: HWND
A handle to the window whose window procedure will receive the message. If this parameter is HWND_BROADCAST ((HWND)0xffff), the message is sent to all top-level windows in the system, including disabled or invisible unowned windows, overlapped windows, and pop-up windows; but the message is not sent to child windows.
Message sending is subject to UIPI. The thread of a process can send messages only to message queues of threads in processes of lesser or equal integrity level.
HWND定义消息接收对象。可以是一个应用程序的句柄,可以是NULL,用于本线程内的程序响应;也可以是HWND_BROADCAST ((HWND)0xffff),对全局广播,所有等层窗口都可以响应事件。
- Msg
Type: UINT
The message to be sent.
For lists of the system-provided messages, see System-Defined Messages.
System-DefinedMessage
- WPARAM wParam
Additional message-specific information.
消息的参数,根据消息类型具体决定参数值及其代表的信息
- LPARAM lParam
Additional message-specific information.
消息的参数,根据消息类型具体决定参数值及其代表的信息
按键消息顺序
每个按键有两个状态消息,键按下(WM_KEYDOWN)和键释放(WM_KEYUP)
对于字符按键,还会有,字符事件(WM_CHAR)响应。提供按下字符的键的ASCII值
- 按下A键产生的消息
消息 | 按键或代码 |
---|---|
WM_KEYDOWN | 「A」的虚拟键码(0x41) |
WM_CHAR | 「a」的字符代码(0x61) |
WM_KEYUP | 「A」的虚拟键码(0x41) |
- Shift + A 产生的消息
消息 | 按键或代码 |
---|---|
WM_KEYDOWN | 虚拟键码VK_SHIFT (0x10) |
WM_KEYDOWN | 「A」的虚拟键码(0x41) |
WM_CHAR | 「A」的字符代码(0x41) |
WM_KEYUP | 「A」的虚拟键码(0x41) |
WM_KEYUP | 虚拟键码VK_SHIFT(0x10) |
常用消息示例
参考资料
https://docs.microsoft.com
https://www.cnblogs.com/huhu0013/p/4651719.html