【发布时间】:2015-01-30 18:33:15
【问题描述】:
我想检测 C++ 中的按键,我需要使用 Windows 系统调用。所以,我做了一些研究,这就是我使用 Hooks 和 Message 得到的结果:
#include <Windows.h>
#include <iostream>
#include <sstream>
#include <fstream>
#include <ctime>
using namespace std;
LRESULT CALLBACK LowLevelKeyboardProc(int code, WPARAM wParam, LPARAM lParam) {
if (code == HC_ACTION) {
switch (wParam) {
case WM_KEYDOWN:
PKBDLLHOOKSTRUCT p = (PKBDLLHOOKSTRUCT)lParam;
char c = char(MapVirtualKey(p->vkCode, MAPVK_VK_TO_CHAR));
cout << c << endl;
}
}
return CallNextHookEx(NULL, code, wParam, lParam);
}
int main() {
HHOOK HKeyboard = SetWindowsHookEx(WH_KEYBOARD_LL, LowLevelKeyboardProc, 0, 0);
MSG msg;
BOOL bRet;
while ((bRet = GetMessage(&msg, NULL, 0, 0)) > 0) {
cout << "bRet = " << bRet << endl; // I want to do something here, but the program doesn't seem to go in here
TranslateMessage(&msg);
DispatchMessage(&msg);
}
UnhookWindowsHookEx(HKeyboard);
return 0;
}
我的问题是为什么我的程序没有进入循环内部(而是停留在 GetMessage 函数上)?我需要它来设置几秒钟后终止的条件,那么我应该把条件放在哪里?我知道 GetMessage 函数读取 Message,但是当我按下键盘上的键时它仍然无法进入,并且回调函数工作正常。
【问题讨论】:
-
没关系。 Windows 内部的挂钩逻辑是直接调用 hook proc - 您只需要消息循环,以便 Windows 知道您的服务线程处于已知的空闲状态。
-
我明白了。但是,既然它根本没有进入循环,我可以只使用
GetMessage(&msg, NULL, 0, 0)而不是整个循环吗?另外,如果想在 10 秒后终止,我的“if process > 10s then terminate”代码会去哪里?
标签: c++ windows console getmessage