C#: How to make a form remember its Bounds and WindowState (Taking dual monitor setups into account)

前端 未结 4 852
说谎
说谎 2020-12-15 10:51

I have made a class which a form can inherit from and it handles form Location, Size and State. And it works nicely. Except for one thing:

When you maximize the app

4条回答
  •  天命终不由人
    2020-12-15 11:28

    There are a few issues with the above solution.

    On multiple screens as well as if the restore screen is smaller.

    It should use Contains(...), rather than IntersectsWith as the control part of the form might otherwise be outside the screen-area.

    I will suggest something along these lines

    bool TestBounds(Rectangle R) {
        if (MdiParent == null) return Screen.AllScreens.Any(ø => ø.Bounds.Contains(R)); // If we don't have an MdiParent, make sure we are entirely on a screen
        var c = MdiParent.Controls.OfType().FirstOrDefault(); // If we do, make sure we are visible within the MdiClient area
        return (c != null && c.ClientRectangle.Contains(R));
    }
    

    and used like this. (Note that I let Windows handle it if the saved values does not work)

    bool BoundsOK=TestBounds(myBounds);
    if (!BoundsOK) {
        myBounds.Location = new Point(8,8); // then try (8,8) , to at least keep the size, if other monitor not currently present, or current is lesser
        BoundsOK = TestBounds(myBounds);
    }
    if (BoundsOK) { //Only change if acceptable, otherwise let Windows handle it
        StartPosition = FormStartPosition.Manual;
        Bounds = myBounds;
        WindowState = Enum.IsDefined(typeof(FormWindowState), myWindowState) ? (FormWindowState)myWindowState : FormWindowState.Normal;
    }
    

提交回复
热议问题