As explained here, the Windows API GetMessage()
blocks until a message is available.
I would like to automatically wake after n seconds. Alternatively, I'd like to have the system post a WM after n seconds. Is there a way to do that?
My current code uses an alternate approach, explained here, where I use a second thread, and have it sleep for n seconds. But the multithreading is causing problems. I'd like to try to use only a single thread, but just make sure it always wakes up after n seconds, even if no other "natural" WM has been posted.
As explained here, the Windows API GetMessage()
blocks until a message is available.
I would like to automatically wake after n seconds. Alternatively, I'd like to have the system post a WM after n seconds. Is there a way to do that?
My current code uses an alternate approach, explained here, where I use a second thread, and have it sleep for n seconds. But the multithreading is causing problems. I'd like to try to use only a single thread, but just make sure it always wakes up after n seconds, even if no other "natural" WM has been posted.
Share Improve this question asked Mar 13 at 22:57 SRobertJamesSRobertJames 9,20516 gold badges70 silver badges123 bronze badges 4 |1 Answer
Reset to default 1As the comments say, this is straightforward. WM_TIMER
is the designated message for this. You call SetTimer
to schedule it, KillTimer
to stop receiving them.
Behind the scenes, there's an optimized mechanism to deliver WM_TIMER
messages. They don't exist as-is in the message queue, but are synthesized when retrieved.
A less-direct answer is to use MsgWaitForMultipleObjectsEx
. This avoids the need for SetTimer/KillTimer
as it directly accepts a timeout value. In addition, it can also check for IO events.
SetTimer
to set a timer to wake you, or change from usingGetMessage
toMsgWaitForMultipleObjects
andPeekMessage
. – Jonathan Potter Commented Mar 13 at 23:17SetTimer
, thenKillTimer
when you get firstWM_TIMER
– 許恩嘉 Commented Mar 14 at 9:55