Pages

Tuesday, November 17, 2009

WindowsFormsHost: Host ActiveX and windows form controls in WPF

If you ever need to host ActiveX control in your wpf application then you can do it by using WindowsFormsHost control. Also sometimes you may need to add windows form control in WPF. you may have developed some controls in windows form technology and you don't want to rewrite this for WPF. WindowsFormsHost control can save you for this time. The following steps describes what to do to add ActiveX or windows form control in wpf application:

1. Add reference to WindowsFromsIntegration assembly which is WindowsFormsIntegration.dll. This is the assembly where WindowsFormsHost control is defined. So if you add WIndowsFormsHost control before adding the assembly reference you''ll find that the WindowsFormsHost control is not recognized in XAML (if you just drag and drop the control form toolbox).

 

2. Add reference to windows forms assembly which is system.windows.forms.dll. You also need to add the namespace in XAML file as shown below:

xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms" 

3. Add reference to the activex control. When you add reference from VS automatically generate an AxHost wrapper for the activex control. Then add the assembly reference in XAML file as shown below:   

xmlns:ax="clr-namespace:AxLib;assembly=AxInterop.AxLib"

FYI, if you try to add the activex dll reference without adding the other two reference you may not get the namespace in the XAML. WindowsFormsHost control can also be used to host any control designed for windows form.

Now you can add your ActiveX control in one of two ways:

1. Add Control directly in XAML as shown below:

<WindowsFormsHost Name="wfHostControl">
      <ax:MyControl x:Name="axMyCtrl"/>
</WindowsFormsHost>

2. Add the control from code by instantiating and placing in the child property of the WindowsFormsHost control.

MyControl ctrl=new MyControl();

wfHostControl.Child = ctrl;

If you need to do something on form load its better to work on WindowsFormsHost control's load event instead of wpf application's load event.

1 comment:

Note: Only a member of this blog may post a comment.