Win32 application will not exit the main loop

This is my main loop:

while(TRUE) { PeekMessage(&msg,hWnd,0,0,PM_REMOVE); if (msg.message==WM_QUIT) break; TranslateMessage(&msg); DispatchMessage(&msg); } 

and this is my callback procedure:

  LRESULT CALLBACK WinProc(HWND hWnd,UINT msg1,WPARAM wParam,LPARAM lParam) { switch(msg1) { case WM_DESTROY : { PostQuitMessage(0); return 0; } break; } return DefWindowProc(hWnd,msg1,wParam,lParam); } 

I found out that when I click the Close button, WM_NCLBUTTONDOWN will be returned by the PeekMessage function in the next loop and without WM_QUIT!

+6
source share
3 answers

the right way to do a message loop

 BOOL bRet; MSG msg; while ((bRet = GetMessage(&msg, hWnd, 0, 0)) != 0) { if (bRet == -1) { // handle the error and possibly exit } else { TranslateMessage(&msg); DispatchMessage(&msg); } } 

You can use PeekMessage if you really need to ... but why are you ignoring the return value?

Also note that this window . I believe that PostQuitMessage for the thread ... I don't remember it from the head, but you may need to pass NULL instead of hWnd .

If you have any other windows that can also capture their message loop, I don't think this is usually a problem, but it could potentially be one; Remember this.

+3
source

Here is the code I found. He should give you something to work with.

  // Main message loop: do { while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } // Run game code here. gTradeApp->ExecuteNextAction(); } while (msg.message != WM_QUIT); 

and WndProc

 LRESULT CALLBACK WndProc(HWND aHWnd, UINT aMessage, WPARAM aWParam, LPARAM aLParam) { switch (aMessage) { case WM_COMMAND: return HandleCommand(aHWnd, aMessage, aWParam, aLParam); case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(aHWnd, aMessage, aWParam, aLParam); } return 0; } 
+2
source

I recommend sticking with this to ensure that the (-1) errors returned by GetMessage are correctly handled:

 while(GetMessage(&Msg, NULL, 0, 0) > 0) { TranslateMessage(&Msg); DispatchMessage(&Msg); } 

In addition, another error does not handle WM_CLOSE properly. Try this so that your program really listens to WM_CLOSE (close button):

 LRESULT CALLBACK WndProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam) { switch(Message) { case WM_CLOSE: { DestroyWindow(hwnd); // this break; } case WM_DESTROY: { PostQuitMessage(0); break; } default: return DefWindowProc(hwnd, Message, wParam, lParam); } return 0; } 
0
source

Source: https://habr.com/ru/post/916937/


All Articles