Is there a Windows API function like Sleep() that works like MessageBoxA()?

119 views Asked by At

When I use MessageBoxA() in a function, it pauses the function but the main program still runs. When I try with Sleep(), it pauses the whole program, not just the function it is in. Why does this happen?

Is there a Windows API function that works like Sleep() but works like MessageBoxA(), pausing only the function it is in, and not the whole program without showing dialog box?

I tried to use Sleep(), but would like to find another function that works like MessageBoxA(). I also tried WaitMessage() but it doesn't work as well.

1

There are 1 answers

1
Remy Lebeau On

MessageBoxA() blocks the calling thread, just like Sleep() does. So, in order for its own dialog window to work correctly, it runs its own message loop internally, receiving and dispatching UI messages. That is why your main UI stays responsive even though the calling thread is blocked.

There is no Sleep-like API function that runs a message loop. You would have to implement that yourself. For instance, by calling MsgWaitForMultipleObjects() in a loop for the duration of your intended sleep interval. If it detects a pending UI message, use PeekMessage() to retrieve the message and DispatchMessage() to let the UI process it, and then go back to waiting for the remaining time left in your sleep interval.

For example:

void SleepButHandleMessages(DWORD sleepMs)
{
    while ((sleepMs != 0) &&
           (MsgWaitForMultipleObjects(0, NULL, FALSE, sleepMs, QS_ALLINPUT) == WAIT_OBJECT_0))
    {
        DWORD startTime = GetTickCount();
        MSG msg;
        while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
        if (sleepMs != INFINITE)
            sleepMs -= (GetTickCount() - startTime);
    }
}

However, a better solution is to simply not block your UI thread to begin with. Instead, move any lengthy operations to a separate worker thread that notifies your UI thread of status updates as needed.