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:

public struct POINT

{

    public Int32    x;
    public Int32    y;

}

public struct MSG

{

    public IntPtr    hwnd;
    public UInt32    message;
    public IntPtr    wParam;
    public IntPtr    lParam;
    public UInt32    time;
    public POINT    pt;
    public UInt32    lPrivate;

}

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.

* FOLLOW-UP **

Errors (1) and (2) are happening during garbage collection.

Sample Code:

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

GC.Collect(); // CAUSE GARBAGE COLLECTION TO EXPOSE BUG

Alternative Managed API:

Do you know one? Please contribute it!

Documentation
PeekMessage on MSDN