Is there a better way to create this game loop? (C ++ / Windows)

I am working on a Windows game and I have this:

bool game_cont;

LRESULT WINAPI WinProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    switch(msg)
    {
    case WM_QUIT: case WM_CLOSE: case WM_DESTROY: game_cont = false; break;
    }
    return DefWindowProc(hWnd, msg, wParam, lParam);
}

int WINAPI WinMain(/*lots of parameters*/)
{
    //tedious initialization

    //game loop
    while(game_cont)
    {
        //give message to WinProc
        if(!GameRun()) game_cont = false;
    }
    return 0;
}

and I am wondering if there is a better way to do this (ignoring the timers & c. right now) than having a game_contglobal one. In short, I need to be able to get out WinMainof WinProc, so that if the user clicks to close the game, otherwise the game than in the game menu, the program will not work in memory. (As it was when I tested it without instructions game_cont..in WinProc.

Oh, and on the side, a note GameRunis basically a bool that returns false when the game ends, and true otherwise.

+3
4

, PeekMessage, .

, :

int Run()
{
    MSG msg;
    while(true)
    {
        if(::PeekMessage(&msg,0,0,0 PM_REMOVE))
        {
            if(msg.message == WM_QUIT || 
                       msg.message == WM_CLOSE || 
                       msg.message == WM_DESTROY)
                break;

            ::TranslateMessage(&msg);
            ::DispatchMessage(&msg);           
        }
        else
        {
            //Run game code
                    if(!GameRun())
                         break;
        }
    }
} 

( )

+10

exit. atexit, WM_CLOSE , .

, , .

+1

game_cont static , WinMain/WinProc, .

0

, .

WM_QUIT - . GetMessage , WM_QUIT.

Your main window will never receive WM_QUIT, because it does not go to the window. WM_CLOSEwill call by default DestroyWindow, so you do not need special processing for this. Process WM_DESTROYby invoking PostQuitMessage, which results WM_QUITin your thread, a special return value from GetMessageand stops the message sending cycle.

0
source

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


All Articles