Hosting a Windows Forms control inside a WPF

Windows Forms can be hosted inside a WPF application using WindowsFormHost. In this post I will show how easily you can use WindowsFormHost to host a windows Form content inside a WPF application.

Step 1:

Create a Windows control library application. Lets put something really simple in it. I have put one Button and one Textbox.

clip_image001

Step 2:

When the button is clicked I have put a MessageBox to show the textbox message.

 private void button1_Click(object sender, EventArgs e)
 {
 MessageBox.Show(string.Format("Hi {0}", this.textBox1.Text)); 
}

Step 3:

Add a WPF application to the Solution and Add reference to the Windows Forms Control library project to it.
clip_image002

Step 4:

Now drag a WindowsFormHost from the Toolbox to the WPF Grid container. The necessary dlls will be added automatically.

clip_image003

Step 5 :

Finally in the constructor of the WPF Control, add the following code :

UserControl1 ctrl = new UserControl1(); 
this.wfh.Child = ctrl;  

Note : We name the WindowsFormHost control as wfh.

Now if you run the application, you will see the Windows Form control is shown inside the WPF content.

Remember, WindowsFormHost has an associated HWND associated with it. Hence it has Airspace issue associated with it. That means it will always rendered above WPF elements (except Popup) and cannot share pixels with WPF content. If you make the UserControl transparent, it will paint the background with the parent control and hence can look like a hack to it.

Download Sample Application

https://skydrive.live.com/embedicon.aspx/.Public?cid=bafa39a62a57009c&sc=documents

Thanks for reading.

Abhishek Sur

Abhishek Sur is a Microsoft MVP since year 2011. He is an architect in the .NET platform. He has profound theoretical insight and years of hands on experience in different .NET products and languages. He leads the Microsoft User Group in Kolkata named KolkataGeeks, and regularly organizes events and seminars in various places for spreading .NET awareness. He is associated with the Microsoft Insider list on WPF and C#, and is in constant touch with product group teams. He blogs at http://www.abhisheksur.com His Book : Visual Studio 2012 and .NET 4.5 Expert Development Cookbook. Follow Abhishek at Twitter : @abhi2434