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.Handle),
0,
0,
PM_REMOVE);
Alternative Managed API:
Do you know one? Please contribute it!
A HandleRef is essentially an IntPtr to a handle and a reference to the object the handle belongs to. Using HandleRef prevents the GC from collecting the object until the native method is done with it.
7/22/2009 9:41:44 AM - -212.251.139.186
An IntPtr is a pointer to a memory location (unmanaged) that adapts to the platform it is running on (64-bit, etc.) UNLIKE a standard int/Integer. You should always use this type for unmanaged calls that require it, even though an int will appear to work on your development machine.
1/13/2008 4:00:13 AM - Damon Carr-72.43.165.29
The mechanism provided by the CLR that enables managed code to call static DLL exports.k
10/27/2022 9:24:28 PM - 114.37.143.20
A HandleRef is essentially an IntPtr to a handle and a reference to the object the handle belongs to. Using HandleRef prevents the GC from collecting the object until the native method is done with it.
7/22/2009 9:41:44 AM - -212.251.139.186
An IntPtr is a pointer to a memory location (unmanaged) that adapts to the platform it is running on (64-bit, etc.) UNLIKE a standard int/Integer. You should always use this type for unmanaged calls that require it, even though an int will appear to work on your development machine.