12

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.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
SharpAffair
  • 5,558
  • 13
  • 78
  • 158

2 Answers2

16

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);
    }
}
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • This works, thank you. Just one glitch I noticed - the embedded form stopped reacting to resizing, it remains fixed size. Any idea how to fix this? – SharpAffair Sep 06 '11 at 13:05
  • Well, that's normal, embedded controls are not normally resizable by the user. Anchor the user control to the bottom and right so it resizes along with the form it is on, changing the size of the embedded form in the process. – Hans Passant Sep 06 '11 at 13:12
  • Both embedded form and user control have Dock set to Fill. The control resizes, but embedded form doesn't. – SharpAffair Sep 06 '11 at 13:24
  • This works fine when I try it with a sample form. I can't guess what might be different with yours. Maybe you can whack it by calling its Invalidate() method in the user control's OnResize override. – Hans Passant Sep 06 '11 at 13:27
1

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