[DllImport("user32.dll")]
static extern bool PeekMessage(out MSG lpMsg, HandleRef hWnd, uint wMsgFilterMin,
uint wMsgFilterMax, uint wRemoveMsg);
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;
}
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.
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.
MSG message = new MSG();
PeekMessage(
out message,
new HandleRef(myWindow,myWindow.hWnd),
0,
0,
PM_REMOVE);
Do you know one? Please contribute it!