Buy Me a Coffee

Buy Me a Coffee!

Thursday, May 3, 2012

WPF Browser Application

Why would you want to do a WPF application in a browser?  Isn’t that what Silverlight is for, letting you do XAML on the Web?  But what if you want to embed something sinister like Visio in a web page?  Will Silverlight let you do that?  No!  At least I don’t think so, If you know how to do it, please let me know, but for the purposes of this blog post, please play along.  Now, to get started, let’s open up a new Visual Studio WPF Browser Application:

First we need to add a reference to the WindowsFormsIntegration part:

Next, we need to get an Interop assembly for the Visio OCX control (AxInterop.Microsoft.Office.Interop.VisOcx).  The prevailing wisdom on the web is to open up a WinForm project and drop a Visio control on the surface to have Visual Studio automatically generate the DLL for us.  I never really like using a hammer to put in screws, so I dug around a little bit and found that aximp is the tool that Microsoft intends you to use for this little task.  So, find your copy of VISOCX.DLL (mine was in C:\Program Files (x86)\Microsoft Office\Office14) and run the following command:
to create your very own interop assembly.  The one creates is named AxVisOcx.dll by default, but it has the same content as the one generated by Visual Studio.  Add a reference to it in your Visual Studio project by using the Browse tab:

You then drop your WindowsFormsHost on the panel or add the following in the xaml:
<WindowsFormsHost HorizontalAlignment="Stretch" Name="windowsFormsHost1" VerticalAlignment="Stretch" />

Add a line to your class for an instance of the AxDrawingControl:

private AxDrawingControl visioControl = new AxDrawingControl();

and then update the constructor for the page to add the control to the WindowsFormsHost:

this.windowsFormsHost1.Child = this.visioControl;

add an event handler for the page loaded event and drop in a line to load your Visio document:

this.visioControl.Src = @"";

and finally, update your project security to a Full Trust Application on the solution properties screen:

Source code: