【问题标题】:Get time to press a key in c++获得时间在 C++ 中按下一个键
【发布时间】:2020-05-12 20:22:45
【问题描述】:
if (a == 1) {
        cout << "Press a" << endl;
        Sleep(500); // I tried to do it this way but it didn't work
        if(GetKeyState('A') & 0x80000){
            cout << "Nice" << endl;
    }}

我没有足够的时间按键,也许你有什么解决办法。

【问题讨论】:

  • 如果您打算像这样将所有内容保存在一个线程中,我强烈建议您切换到State Machine Design
  • GetKeyState 反映了上次处理消息时的键盘状态,并且您的循环未处理任何消息。请改用GetAsyncKeyState。请注意,您必须在调用函数的确切时间按住键才能看到它。

标签: c++ winapi time


【解决方案1】:

@JonathanPotter 指出了一个解决方案。

以下是为我工作的示例代码。你可以试试看有没有帮助。

GetAsyncKeyStateGetKeyState 返回SHORT,因此将返回值与0x8000 进行比较,而不是0x80000

DWORD WINAPI MyThreadFunc(LPVOID lpParam)
{
    while (TRUE)
    {
        if (GetAsyncKeyState(0x41) & 0x8000) {
            cout << "Nice" << endl;
            return TRUE;
        }
    }
}


int main()
{
    HANDLE threadHdl = CreateThread(NULL, 0, MyThreadFunc, NULL, 0, NULL);
    if (threadHdl == NULL)
    {
        DWORD errCode = GetLastError();
        cout << "CreateThread fails with error: " << errCode;
        return FALSE;
    }

    cout << "Press a" << endl;

    WaitForSingleObject(threadHdl, INFINITE);
}

【讨论】:

  • GetLastError 的返回值在你调用它的时候是没有意义的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-02
  • 1970-01-01
  • 2012-11-09
相关资源
最近更新 更多