SharpAffair
SharpAffair

Reputation: 5488

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.

Upvotes: 12

Views: 7432

Answers (2)

Tobin Cavanaugh
Tobin Cavanaugh

Reputation: 36

Going off of what Hans Passant said, I found that if the control you are putting the form into is a Flow Layout Panel, disabling WrapContents will fix an alignment issue where the contents aren't placed inline with the FlowDirection.

        public void EmbedForm(Form frm)
        {
            frm.TopLevel = false;
            frm.FormBorderStyle = FormBorderStyle.None;
            frm.Visible = true;

            FLP_Inspector.WrapContents = false;
            FLP_Inspector.Controls.Add(frm);
        }

Upvotes: 1

Hans Passant
Hans Passant

Reputation: 942408

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);
    }
}

Upvotes: 16

Related Questions