PeekMessage (user32)
Last changed: -93.84.11.72

.
Summary

User-Defined Types:

  [StructLayout(LayoutKind.Sequential)]
  public struct NativeMessage
  {
      public IntPtr handle;
      public uint msg;
      public IntPtr wParam;
      public IntPtr lParam;
      public uint time;
      public System.Drawing.Point p;
  }

C# Signature:

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool PeekMessage(out NativeMessage lpMsg, HandleRef hWnd, uint wMsgFilterMin,
   uint wMsgFilterMax, uint wRemoveMsg);

User-Defined Types:

None.

Notes:

Specifying HandleRef instead of IntPtr as the hWnd type prevents the object the handle referees to from being garbage collected. All internal Microsoft PInvokes use HandleRef and not IntPtr.

Do not use System.Windows.Forms.Message for the first argument - this is a different data structure.

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 NativeMessage 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:

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

Alternative Managed API:

Based off of Tom Miller's blog. Modified to comply with VS.Net 2005 static code analysis (i.e. proper MarshalAs attributes) and eliminate the refrence to WindowMessage.

( See: https://blogs.msdn.com/tmiller/archive/2005/05/05/415008.aspx )

C# Signature:

  [SuppressUnmanagedCodeSecurity]
  [return: MarshalAs(UnmanagedType.Bool)]
  [DllImport("User32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  public static extern bool PeekMessage(out NativeMessage message, IntPtr handle, uint filterMin, uint filterMax, uint flags);

Sample Code:

  NativeMessage msg;
  bool foundMessage = PeekMessage(out msg, IntPtr.Zero, 0, 0, 0);

Documentation
PeekMessage on MSDN