c++ - 不进入控制台应用程序的 Windows GetMessage 循环

标签 c++ windows console getmessage

我想在 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 窗口(例如 RegisterClassCreateWindow),而不是控制台窗口。

如果您只想让回调在特定时间段内工作,您可以使用可提醒等待,例如 SleepExMsgWaitForMultipleObjects,它们接受超时。

关于c++ - 不进入控制台应用程序的 Windows GetMessage 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28242447/

相关文章:

C++ ':chcp' 不是内部或外部命令,也不是可运行的程序或批处理文件

c++ - 未知模块 QT : webkit

c - 未声明的 WinApi Commctrl 轨迹栏标识符

WINDOWS 上的 Python flask 双栈(ipv4 和 ipv6)

c# - 网络层如何监听?

javascript - Chrome 控制台输出中的 "less than dot"符号是什么意思?

c++ - 两行后 fstream 没有从文本文件中读取

console - system.console NullPointerException

c++ - 在C++中将破折号分隔的文件中的数字插入BST

c++ - 通过 std::shared_ptr 强制执行对象