Introduction
In my previous tip, "Hosting windows form user control in MFC dialog", we discussed about how to host Windows Form user controls in MFC dialog box and integrate MFC with .NET platform with CLI technology. Now, we'll talk about How to host Windows Form in Windows user control. My idea of this tip/trick and previous tip/trick is to reach a solution for using Windows Forms in MFC dialog and integrate .NET Forms with MFC forms.
Background
Before reading this tip/trick, please read about user control from here.
Using the Code
Note: If I have a Windows Form in my project, I could not set parent before initializing Form "TopLevel
" properties with false
value, and if I do it (set parent object before than), I get an Error.
- Open Visual Studio
- Create Windows Forms Control Library and set then name of project, for example. "
WinFormUserControl
". - Drag button control to the
UserControl1
place and set Dock
property to "Button
". - Drag panel control to the
UserControl1
place and set Dock
property to "Fill
".
Now we have a Windows Forms Control Library project with one User Control, Button and Panel Control. The name of the user control is
UserControl1
and panel is
Panel1
. After that, we add a Windows Form in our project, we can set the name of new form to "
ChildForm
". At this step, we can overload the
Show()
method of form as follows:
public partial class ChildForm : Form
{
public ChildForm()
{
InitializeComponent();
}
public void Show(Panel parentObject)
{
if (parentObject != null)
{
this.TopLevel = false;
this.Parent = parentObject;
}
this.Show();
}
}
Now we should instantiate "ChildForm
" in button1 click()
event and call overloaded Show(Panel parentObject)
method for hosting Windows Form in panel.
public partial class UserControl1: UserControl
{
public UserControl1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
ChildForm childForm = new ChildForm();
childForm.Show(this.panel1);
}
}
Congratulations. Please run your project and click on Button1
.
History
- May 1, 2013: First published