我想在 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,但是当我按下键盘上的键时它仍然没有进入并且回调函数工作正常。
最佳答案
事件发布到事件窗口。控制台窗口由控制台子系统 csrss.exe 拥有,它接收事件,然后将它们转换为字符并将它们放入控制台对象中,该对象是应用程序的 stdin
。
如果您想以 Win32 GUI 方式处理事件,您应该使用 Win32 窗口(例如 RegisterClass
和 CreateWindow
),而不是控制台窗口。
如果您只想让回调在特定时间段内工作,您可以使用可提醒等待,例如 SleepEx
或 MsgWaitForMultipleObjects
,它们接受超时。
关于c++ - 不进入控制台应用程序的 Windows GetMessage 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28242447/