PeekMessage (user32)
Last changed: -93.84.11.72

.
Summary

C# Signature:

[DllImport("user32.dll")]
static extern bool PeekMessage(out MSG lpMsg, HandleRef hWnd, uint wMsgFilterMin,
   uint wMsgFilterMax, uint wRemoveMsg);

User-Defined Types:

None.

Notes:

Specifing HandleRef instead of IntPtr as the hWnd type prevents the handle from going out of scope. All internal Microsoft PInvokes use HandleRef and not IntPtr.

Tips & Tricks:

I have been seeing with this interface that occasionally PeekMessage will thrown a couple different types of exceptions.

(1) "Object reference not set to an instance of an object."

(2) "External component has thrown an exception."

As seen below, "message" is the culprit. After exception (1) occurs, all the data members of MSG are zero. Even the point is initialized. After exception (2) occurs, the external dll crashes and it brings down your app. I have tried using GC.KeepAlive(message); without luck.

Sample Code:

MSG message = new MSG();
PeekMessage(
    out message,
    new HandleRef(myWindow,myWindow.hWnd),
    0,
    0,
    PM_REMOVE);

Alternative Managed API:

Do you know one? Please contribute it!

Documentation
PeekMessage on MSDN