Game loop in Win32 API
Asked Answered
G

3

6

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 ).

Gauge answered 12/5, 2010 at 8:35 Comment(1)
Really stupid question but you have got a windows proc to handle the windows messages, right?Latvina
B
6

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.

Bullshit answered 12/5, 2010 at 10:33 Comment(0)
H
5

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.

Hilariahilario answered 12/5, 2010 at 8:52 Comment(0)
D
2

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);     
Disavow answered 12/5, 2010 at 11:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.