windows DoEvents 等效于 C++?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1415095/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
DoEvents equivalent for C++?
提问by jmasterx
I'm new to native c++. Right now, I made it so when I press the left mouse button, it has a for loop that does InvalidateRect and draws a rectangle, and increments X by the box size each time it iterates. But, C++ is so much faster and efficient at drawing than C# that, it draws all this instantly. What I would like is for it to invalidate the rectangle, show the rectangle, wait 50ms, then continue the loop. I tried Sleep(50) but it still waits until painting is done before showing the result. I also tried PeekMessage but it did not change anything. Any help would be appreciated. Thanks
我是本机 C++ 的新手。现在,我做到了,当我按下鼠标左键时,它有一个 for 循环,它执行 InvalidateRect 并绘制一个矩形,并在每次迭代时按框大小增加 X。但是,C++ 的绘图速度和效率比 C# 快得多,它可以立即绘制所有这些。我想要的是它使矩形无效,显示矩形,等待 50 毫秒,然后继续循环。我试过 Sleep(50) 但它仍然等到绘画完成后再显示结果。我也试过 PeekMessage 但它没有改变任何东西。任何帮助,将不胜感激。谢谢
回答by Reed Copsey
DoEvents basically translates as:
DoEvents 基本上翻译为:
void DoEvents()
{
MSG msg;
BOOL result;
while ( ::PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE ) )
{
result = ::GetMessage(&msg, NULL, 0, 0);
if (result == 0) // WM_QUIT
{
::PostQuitMessage(msg.wParam);
break;
}
else if (result == -1)
{
// Handle errors/exit application, etc.
}
else
{
::TranslateMessage(&msg);
:: DispatchMessage(&msg);
}
}
}
回答by Magnus Hoff
I am a bit rusty in Win32 API, but the asynchronous way of doing this would be:
我对 Win32 API 有点生疏,但是这样做的异步方式是:
- Invalidate the rect
- Set a timer (see below) to send a message after 50ms
- Return to the event loop to let WM_PAINT events happen
- On receiving the timer message, move the rect, then repeat
- 使矩形无效
- 设置一个计时器(见下文)以在 50 毫秒后发送消息
- 返回事件循环让 WM_PAINT 事件发生
- 收到定时器消息后,移动矩形,然后重复
This way integrates nicely with being event driven. I realize this is not exactly what you ask for, but I thought I'd mention it as a possible solution anyway :)
这种方式与事件驱动很好地集成在一起。我意识到这并不完全是您所要求的,但我想无论如何我都会提到它作为可能的解决方案:)
EDIT: A quick google turns up the Windows API call [SetTimer](http://msdn.microsoft.com/en-us/library/ms644906(VS.85,loband).aspx)which you can use to facilitate this. The message will be a WM_TIMER one.
编辑:一个快速的谷歌打开了 Windows API 调用 [SetTimer]( http://msdn.microsoft.com/en-us/library/ms644906(VS.85,loband).aspx),您可以使用它来促进这一点。该消息将是 WM_TIMER 消息。