简体   繁体   English

等待Win32应用程序中的特定键

[英]Wait for a specific key in a Win32 application

At some point in my program, I want to wait for the user to either press [return] or [escape]. 在程序的某个时刻,我想等待用户按下[return]或[escape]。 This is what I did: 这是我所做的:

while(1)
{
    Sleep(100);
    if( GetAsyncKeyState( VK_RETURN ) )
    {
        //do something
    }
    if( GetAsyncKeyState( VK_ESCAPE ) )
    {
        //do something else 
    }   
}

But (only in the release build) after waiting for about 2 seconds, Windows says it's not responding, and it crashes. 但是(仅在发行版中)等待约2秒钟后,Windows表示它没有响应,并且崩溃了。 What should I do? 我该怎么办?

Your application is a GUI subsystem application and its main thread must regularly pump its message queue. 您的应用程序是GUI子系统应用程序,其主线程必须定期抽取其消息队列。 You are not doing that because you enter a tight loop looking for specific key state. 您之所以没有这样做,是因为您进入一个紧密的循环来寻找特定的键状态。 Because you don't service your queue, the system concludes that your application is broken and ghosts your window. 因为你不服务你的队列,系统推断出你的应用程序被破坏, 你的窗口。

Before we go on to how to do it right, your existing approach is broken in other ways. 在我们继续做正确的事情之前,您现有的方法已经以其他方式被破坏了。 Suppose that the key is pressed and released during the Sleep(100). 假设在Sleep(100)期间按下并释放了该键。 Then you miss that event. 然后,您会错过该活动。 Or suppose your app is not in the foreground. 或假设您的应用程序不在前台。 Then it responds to key presses meant for other applications. 然后,它响应用于其他应用程序的按键。

To solve the problem you simply need to let your normal message loop process and dispatch messages. 要解决该问题,您只需要让正常的消息循环处理并调度消息即可。 When you get a WM_KEYDOWN message for the appropriate key you can react accordingly. 当您收到相应密钥的WM_KEYDOWN消息时,您可以做出相应的反应。

Using the message loop in the intended way not only fixes the behaviour you observe in the question, but also the issues I describe above. 以预期的方式使用消息循环不仅可以解决您在问题中观察到的行为,还可以解决我在上面描述的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM