Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Form to a UserControl - is this possible?

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.

like image 217
SharpAffair Avatar asked Sep 06 '11 12:09

SharpAffair


People also ask

What is the difference between user control and form?

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.

How do I create a new form in Winforms?

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.


1 Answers

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);
    }
}
like image 137
Hans Passant Avatar answered Oct 12 '22 03:10

Hans Passant