I have an application with one main window. In the window, you click on a button that spawns other windows. I was wondering if anybody knew how to keep these spawned windows within the original window and not let it be able to be dragged out of it?
The easier way of doing this (and more advisable) is to make your main form an MDI container. You can set this in the designer by setting IsMdiContainer
to true in the properties window for the main form. To add a form to the MDI parent, just set the MdiParent
property of the new form to the instance of the main form. For example, say this code is in a button on the MDI form:
void button1_Click(object sender, EventArgs e)
{
Form newForm = new Form(); // obviously you'd use your own Form class here
newForm.MdiParent = this;
newForm.Show();
}
However, you can add a new Form as a child of an existing Form and it will behave just like any other control, but you have to set the TopLevel
property to false before the Form is shown. Our code would look like this:
void button1_Click(object sender, EventArgs e)
{
Form newForm = new Form(); // obviously you'd use your own Form class here
newForm.TopLevel = false;
newForm.Parent = this;
newForm.Show();
}
The MDI approach is what's generally recommended, mainly because that's exactly what the feature was designed to do: have a container Form that manages zero or more child Forms.