Original Post
I've seen people asking here and there about the best way to implement a message loop in .NET, and wasn't able to locate any other posts on the topic, so I thought I'd share the way I do it, as much to get input on any potential problems with the technique as anything. Quite simply, I do it exactly the same way as I'd make a message loop when programming for the Windows API in C++. If you use C#, you need to mess around with P/Invoke stuff, but if you use Managed C++ it's just a matter of a few lines of code. So to start off with the Managed C++ version it's as simple as this... My question is, is there anything wrong with handling Windows message processing this way? I haven't run into any problems, but my with .NET there's a hidden "gotchya" waiting in the shadows as often as not. One thing I should note, is that while it should be possible to do the same thing in C# by defining the necessary structures and importing the necessary functions (see www.pinvoke.net for a reference on how to do this), in my limited experience trying to do so it doesn't actually work. The problem is that calling PeekMessage seems to randomly throw exceptions for no discernable reason. Anybody have any experience that could shed some light on why this might be? I see that this problem is documented on the pinvoke.net site, but there's no indication of any solution. Specifically, I get this problem when I do the same as above using the following definitions (cut and pasted from pinvoke.net really)...
#include <windows.h>
...
System::Windows::Form ^mainWindow;
...
// Here's your very simple message loop.
MSG message;
while(mainWindow->Created)
{
while( PeekMessage( &message, (HWND)mainWindow->Handle.ToPointer(), 0, 0, PM_REMOVE ) )
{
TranslateMessage( &message );
DispatchMessage( &message );
if( !mainWindow->Created )
break;
}
}
[StructLayout(LayoutKind.Sequential)]
public struct MSG
{
public IntPtr hwnd;
public uint message;
public IntPtr wParam;
public IntPtr lParam;
public uint time;
public POINT pt;
}
[DllImport("user32.dll")]
static extern bool PeekMessage(out MSG lpMsg, HandleRef hWnd, uint MsgFilterMin, uint wMsgFilterMax, uint wRemoveMsg);
[DllImport("user32.dll")]
static extern bool TranslateMessage([In] ref MSG lpMsg);
[DllImport("user32.dll")]
static extern IntPtr DispatchMessage([In] ref MSG lpmsg);