Andrej Tozon's blog

In the Attic

NAVIGATION - SEARCH

You've got mail: Windows Forms & WPF interop

One of my favorite samples when talking about WPF is showing a rotating 3D letter 'e' in a Windows Forms application. You know, something like those "you've got mail" computer messages, seen in many Hollywood movies. Windows Forms/WPF interoperability features make this kind of stunt very easy to pull off and this is the recipe to make in happen in 15 minutes...

First, you'll have to come up with some kind of 3D element, which you can import in WPF. I used electric rain's ZAM 3D tool, which has the ability to export 3D elements directly to XAML, which can be later picked up and additionally arranged with  Expression Blend, for example. It actually took me just a couple of minutes to create a 3D letter 'e' and import the scene into Blend.

blendmail1

Rotating the 3D element was done by animating ViewPort's camera by setting 5 progressive key frames of its Rotate Transform property.

image

We need to make the element reusable, so we'll transform it to a user control. Expression Blend 2 (currently still in CTP version) fortunately makes this task very easy by exposing the "Make Control" task (Tools | Make Control...)

OK, half done... We now have a user control with rotating 3D element and a WPF Window, simply displaying it.

The next step is adding a new Windows Form to the project. Save the project in Blend, switch over to Visual Studio (2008) and add a new Form. Visual Studio will make sure all necessary interop assemblies will be added to the project in this process.

With newly created form displayed in the designer area and open a Toolbox. Right at the top (or elsewhere, depending on your project's name), there should be your WPF user control, ready to drag onto the form. When doing so, Visual Studio will create your control, hosted in the ElementHost control (a Windows Forms control, which can host a WPF element). Set control's size to a desired value and you're done.

image

Download the sample project here.