SimConnect and WPFPosted: February 11, 2008
I’ve noticed some folks having problems using SimConnect with WPF based apps because there’s no easily accessed hWnd and no easily overridden DefWndProc. Here’s a solution that works around those problems and is also usable in WinForms apps if you like.
In the existing managed samples provided in the SDK, the 2nd param of the new SimConnect(…) line is the hWnd and the 3rd param is the WM_Xxx based message to send to the main window. For this solution, we will instead pass 0 for both of those params and pass an AutoReset EventWaitHandle object as the 4th param to that call. Then we will create a background thread that waits for this event to fire and then calls the ReceiveMessage function to handle data received from SimConnect.
Here’s a couple of code snippets:
This first snippet shows the data used:
And this next snippet shows the code that uses these data items:
With the code above, all of the OnRecvXxx callbacks will still happen on the UI thread context, meaning the rest of your code can stay the same as it was when using the hWnd and WM_Xxx message with an overridden DefWndProc.
If you would prefer that the message handling and the OnRecvXxx callbacks occur on the background thread context, you can do that with this code snippet instead:
Doing things this way will require you to handle any thread synchronization that might be required to access any UI elements within each OnRecvXxx callback, but if you aren’t accessing UI elements much in your callbacks, then the 2nd way might be more efficient overall, but will require more work on your part to insure things happen on the correct thread.
I’ve been playing around with WPF for the last couple of weeks and its a lot of fun and can do some really cool things (repeat after me, DataTemplates are your friend :-> ). Hopefully the above code snippets will let folks out there write some cool WPF based SimConnect clients.
Tim "Beatle" Gregson