Austin
Austin

Reputation: 165

Stop form from exiting parent form

I am not asking for my code to be written for me but rather a path.

I am looking for a way to prevent a form that open from leaving the bounds of the parent form.

Like keep both forms open, but not allow another form that is opened via the program to leave the bounds of the other program. Best example is like an operating system.

Picture of what I mean:

enter image description here

Thank you, any further questions please ask! Austin

Upvotes: 1

Views: 621

Answers (1)

Jason W
Jason W

Reputation: 13199

An MDI solution is a starting point, but the child mdi forms can still be moved outside the bounds of the visible window of the parent MDI form. To address this issue, you'll need to add an event handler to the child MDI forms so that after each child window is moved, it remains contained in the parent MDI form.

The sample code below is from a very old question on the MSDN forums, but still works like a charm :) Source: https://social.msdn.microsoft.com/Forums/windows/en-US/46e35e80-7bfa-447a-9655-965134124f70/prevent-child-form-from-leaving-parent-form-bounds?forum=winforms

protected override void OnMove(EventArgs e)
{
    //
    // Get the MDI Client window reference
    //
    MdiClient mdiClient = null;
    foreach(Control ctl in MdiParent.Controls)
    {
        mdiClient = ctl as MdiClient;
        if(mdiClient != null)
            break;
    }
    //
    // Don't allow moving form outside of MDI client bounds
    //
    if(Left < mdiClient.ClientRectangle.Left)
        Left = mdiClient.ClientRectangle.Left;
    if(Top < mdiClient.ClientRectangle.Top)
        Top = mdiClient.ClientRectangle.Top;
    if(Top + Height > mdiClient.ClientRectangle.Height)
        Top = mdiClient.ClientRectangle.Height - Height;
    if(Left + Width > mdiClient.ClientRectangle.Width)
        Left = mdiClient.ClientRectangle.Width - Width;
    base.OnMove(e);
}

Upvotes: 3

Related Questions