Normally, controls are being added to forms. But I need to do an opposite thing - add a Form instance to container user control.
The reason behind this is that I need to embed a third-party application into my own. Converting the form to a user control is not feasible due to complexity.
User controls are a way of making a custom, reusable component. A user control can contain other controls but must be hosted by a form. Windows forms are the container for controls, including user controls. While it contains many similar attributes as a user control, it's primary purpose is to host controls.
Add a new formRight-click on the project and choose Add > Form (Windows Forms). In the Name box, type a name for your form, such as MyNewForm. Visual Studio will provide a default and unique name that you may use.
This is possible by setting the form's TopLevel property to false. Which turns it into a child window, almost indistinguishable from a UserControl. Here's a sample user control with the required code:
public partial class UserControl1 : UserControl {
public UserControl1() {
InitializeComponent();
}
public void EmbedForm(Form frm) {
frm.TopLevel = false;
frm.FormBorderStyle = FormBorderStyle.None;
frm.Visible = true;
frm.Dock = DockStyle.Fill; // optional
this.Controls.Add(frm);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With