WindowsApi:PeekMessage
lastmod 2016-04-13created 2016-04-132 edits
Clear message queue
While developing a Mobile Application, I had a case where a certain event took about 3 seconds from when it fired until it finished, and I needed to prevent other events from firing during that time. The first thing I tried was setting Form.Enable = false and setting it back to true after 3 seconds. In this case, the events fired after the 3 seconds passed. So I looked for a way to remove all Messages from the Message Queue.
The first thing that came to mind was IMessageFilter, the message-related interface, but this interface is not provided in the Compact Framework. I found code that implements IMessageFilter directly to receive Messages, but that code required passing a Control as a parameter. Unfortunately (?), this code (which takes a Control as a parameter) could not be used in the Application I was developing. So I searched again and found the method below.
struct MSG
{
IntPtr hwnd;
uint message;
IntPtr wParam;
IntPtr lParam;
int time;
int ptX;
int ptY;
}
[DllImport("coredll")]
extern static bool PeekMessage(out MSG Msg, uint hWnd, uint
wMsgFilterMin, uint wMsgFilterMax, uint wRemoveMsg);
const uint PM_REMOVE = 1;
public static void ClearMessages()
{
MSG msg;
while (PeekMessage(out msg, 0, 0, 0, PM_REMOVE)) ;
}
Here you can see that because the Message structure is not defined in the Compact Framework, a struct called MSG was created manually, and that PM_REMOVE(1) is a parameter that removes all messages one message from the Message Queue.