Wednesday, June 02, 2004
« Short-Timer's Disease | Main | Close() vs Dispose() »

I owe lunch to a great friend of mine for helping my solve this.  Jason Walker (a fellow member of our .NET User Group leadership) was kind enough to research an issue I was having.

The team up at Redmond was kind enough to include a method called EnableVisualStyles() in .NET Framework v1.1.  This method alleviates the need to include .manifest files for each .exe for which you want the sleek, cool Windows XP look and feel.  This method should be called prior to any UI or control being presented so it is routinely the first line of code in your app's entry point.  I suppose (for I haven't looked deeply into it yet) that calling this method internally performs a PostMessage() operation which is an asynchronous, fire and forget method (vs SendMessage() which is synchronous).

Through heartache and pain I have found that if your application displays a modal dialog window an exception will be thrown when the dialog closes down.  Well, I was programming along and all of the sudden I was greeted by a very noxious-looking and uninformative System.Runtime.InteropServices.SEHException when a wizard that I had written (which is displayed as a modal dialog) shut down.  It didn't occur to me that my call to EnableVisualStyles() was the offender of this obscure error.  I was trying to figure out whether it was something to do with some custom non-UI to UI thread marshalling or something of the like.  The stack trace revealed the following:

SEHException at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg) at
System.Windows.Forms.ComponentManager.System.Windows.Forms.UnsafeNativeMethods+IMsoComponentManager.FPushMessageLoop(...)
...

I should have read the stack trace more closely before applying my own rationale to solving the problem.

The solution is to call Application.DoEvents() just following the call to Application.EnableVisualStyles() so that the message posted has a chance to complete before proceeding.