Monday, April 06, 2009

Enable “Modern” (Themed) Common Controls in Hybrid WPF/WinForms Apps

Here is a quick hint to save someone from a bunch of Googling:

If you are building a WPF app, you may find that you need or want to also use some Windows Forms windows. In my case, I was adding a form just to host a WinForms control, so there was no point in creating a WPF form just to host the WinForms Host container in order to add the control. A more common scenario is you want to invoke a built-in Windows dialog box, which is not natively a WPF object.

If you do this, it will work, but you will notice that some controls are rendering their old-fashioned look and behavior – you’ll be zapped back to the era of Win 2000 or the earliest .Net apps that lacked the benefit of comctl32.dll version 6. Square edges, no mouse-hover behaviors, etc.

The short answer for how to fix this is that you need to add a call to System.Windows.Forms.Application.EnableVisualStyles().

Add it once, somewhere early on. It’s ideal (though not always necessary) to do this before you start instantiating the WinForms objects.

Apparently the template code for WinForms projects contains this line, and depending on your POV, that’s either “low level boilerplate that an app developer shouldn’t have to care about” or “the kind of thing that kids nowadays just take fer granted with their magical IDEs and WYSI-whatnot, virtual memory and lazy programming habits.”

I was also particularly motivated to write this post because the most accurate (and earliest) Google hit I found on this topic was to one of those scam programmer support boards, where they wanted me to sign up for a trial with a credit card just to see the discussion thread on this issue.

Which is half insane if they could persuade me that had the right answer inside, but 100% insane since there was no way for me to know that their “answers” weren’t way off topic from clueless n00b who thinks a HWND is what you pull to keep the rain out of your office.

0 comments: