Game loop in Win32 API

2019-01-23 20:24发布

I'm creating game mario like in win32 GDI . I've implemented the new loop for game :

PeekMessage(&msg,NULL,0,0,PM_NOREMOVE);

while (msg.message!=WM_QUIT)
{
    if (PeekMessage(&msg,NULL,0,0,PM_REMOVE)) {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    else // No message to do
    {
        gGameMain->GameLoop();  
    }
}

But my game just running until I press Ctrl + Alt + Del ( mouse cursor is rolling ).

3条回答
闹够了就滚
2楼-- · 2019-01-23 21:00

I've always been using something like that:

    MSG msg;
    while (running){
        if (PeekMessage(&msg, hWnd, 0, 0, PM_REMOVE)){
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
        else
            try{
                onIdle();
            }
            catch(std::exception& e){
                onError(e.what());
                close();
            }
    }

onIdle is actual game lopp implementation, onError() is an error handler (takes error description as argument), and "running" is either a global bool variable or a class member. Setting "running" to false shuts down the game.

查看更多
何必那么认真
3楼-- · 2019-01-23 21:17

I guess the program may ask user for continue or exit, inside GameLoop function call. On exit Post WM_QUIT message to the window.

PostMessage(hWnd, WM_QUIT, 0, 0 );

hWnd-> The handle of the game window

else make a call to

DestroyWindow(hWnd);

This will send a WM_DESTROY to your window procedure. There you can call

PostQuitMessage(0);     
查看更多
劫难
4楼-- · 2019-01-23 21:19

I think this really depends on your context. Windows will only send a WM_QUIT in response to your application calling PostQuitMessage. A common (if not great) solution here is to use a bool to exit the message loop when your program wants to end.

查看更多
登录 后发表回答