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.
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.
Step 4:
Now drag a WindowsFormHost
from the Toolbox to the WPF Grid container
. The necessary dlls will be added automatically.
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.