不在控制台应用程序的Windows GetMessage循环内 [英] does not go inside the Windows GetMessage loop on console application
问题描述
我想检测C ++中的按键,因此我需要使用Windows系统调用。因此,我做了一些研究,这就是我使用Hooks and Message所得到的:
I want to detect keypress in C++ and i need to use Windows System Call. So, i did some research and this is what i got using Hooks and 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,但是当我按键盘上的键时,它仍然无法进入,并且回调函数也可以正常工作。
My question is why my program doesn't go inside the loop(and instead stuck on GetMessage function)? I need it to set conditions to terminate after some seconds, so where should i put the conditions? I know the GetMessage function reads Message, but when i press keys on my keyboard it still not going in and the callback function works just fine.
推荐答案
事件被发布到活动窗口。控制台窗口由控制台子系统csrss.exe拥有,它接收事件,然后将其转换为字符并将其放入控制台对象,该对象是应用程序的 stdin
。
The events are posted to the active window. Console windows are owned by the console subsystem, csrss.exe, and it receives the events, then translates them to characters and puts them in the console object which is your application's stdin
.
如果要以Win32 GUI方式处理事件,则应使用Win32窗口(例如 RegisterClass
和 CreateWindow
),而不是控制台窗口。
If you want to process events the Win32 GUI way, you should use a Win32 window (e.g. RegisterClass
and CreateWindow
), not a console window.
如果您只希望回调在一段时间内有效,您可以使用警报提醒,例如 SleepEx
或 MsgWaitForMultipleObjects
,它们接受超时。
If you just want the callbacks to work for a certain period of time, you can use an alertable wait such as SleepEx
or MsgWaitForMultipleObjects
, which accept a timeout.
这篇关于不在控制台应用程序的Windows GetMessage循环内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!