admin管理员组

文章数量:1391951

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
  • 4 Either use SetTimer to set a timer to wake you, or change from using GetMessage to MsgWaitForMultipleObjects and PeekMessage. – Jonathan Potter Commented Mar 13 at 23:17
  • It sounds like a big potential abuse. You have to explain your ultimate goal, otherwise, you are at risk of solving an XY Problem. – Sergey A Kryukov Commented Mar 14 at 3:18
  • You should find some help here devblogs.microsoft/oldnewthing/20050217-00/?p=36423 – Simon Mourier Commented Mar 14 at 7:58
  • SetTimer , then KillTimer when you get first WM_TIMER – 許恩嘉 Commented Mar 14 at 9:55
Add a comment  | 

1 Answer 1

Reset to default 1

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

本文标签: windowsIs there a way to automatically wake a WinAPI GetMessage() after n secondsStack Overflow