C++Winapi while loop解决方法

C++ Winapi while-loop workaround?

本文关键字:方法 解决 loop while C++Winapi      更新时间:2023-10-16

所以,我有一个普通的while循环(如图所示),当我的程序在while循环中运行很长一段时间时,窗口变得没有响应,说"废话废话没有响应。"好吧。。。我知道在WinAPI中我应该使用SetTimer()函数和WM_TIMER,但你猜怎么着!我这次编程是为了好玩,我想知道是否有变通办法。。。比如在while循环中放入一些东西,使其保持"响应性"。我不是想破坏别人。

这是代码:

while (battleupdate == 1)
{
    RECT wrect;
    wrect.left   = 0;
    wrect.right  = 570;
    wrect.top    = 0;
    wrect.bottom = 432;
    if (FILLRECT == 0){
    FillRect(hdc, &wrect, (HBRUSH) GetStockObject (WHITE_BRUSH));
    cout << "battleupdated" << endl; FILLRECT = 1; }

    /*OPPONENT STATS*/        
    if (1 == 1) {   stringstream stream; stream << opname << "            ";        
        TextOut (hdc, 20, 50, stream.str().c_str(), 12); }
    //if (1 == 1) {   stringstream stream; stream << itemslot4name << "        ";        
        //TextOut (hdc, 465, 188, stream.str().c_str(), 12); }
    //if (1 == 1) {   stringstream stream; stream << itemslot4effect << "   ";        
        //TextOut (hdc, 465, 204, stream.str().c_str(), 4); }
        battleupdate = 1; 
        //I DON'T CARE IF MY DELAY CODE IS LAME YES I KNOW ABOUT SLEEP().
        while (delay > 0)
        {
            delay -= 1;
        }
        if (delay == 0)
        {
            delay = resetdelay;
        }
    }

我所问的可能吗?

我很感激任何答案,即使是"不,不能那样做,你最好使用WM_TIMER!"因此,提前感谢您的回答!

  • 操作系统:windows 7终极

  • 编译器:Dev-C++

  • 其他:使用winapi

如您所知,您应该使用计时器来处理您的逻辑。。。

但如果你真的不想这样做,你可以使用"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);
    }
  }
}

在while循环中,您只需要定期调用"DoEvents"。。。