简体   繁体   中英

What's the safest way to adjust my WinForms application main form starting size and position at run time?

A WinForms application of mine makes serious use of screen area and would better be given as much as possible. At the same time I would not like to ignore small screen users. I also find it a bad manner to make an application to start in maximized mode by default. Moreover, I seek to deliver reasonable behavior without need to store and read configuration in files/registry.

So what I seek to do is to set the main form size at the application start time, setting it to something like Width = Screen.PrimaryScreen.WorkingArea.Width * 85 / 100; (and the same thing with height).

And this works but the problem is that the form bottom and right edges usually go beyond the screen in this case even though it is perfectly possible to fit the screen nicely if positioned properly.

What is the way to adjust the main form position effectively?

Maybe you did not set the formposition.

First , Set

    this.StartPosition = FormStartPosition.Manual;

If you didn't set it , the this.locatin command won't ever work.

Next

    this.Location = new Point(0, 0);

It should works

Set the Location to center the form based on the size you've chosen:

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);

    this.Width = Screen.PrimaryScreen.WorkingArea.Width * 85 / 100;
    this.Height = Screen.PrimaryScreen.WorkingArea.Height * 85 / 100;
    this.Location = new Point(Screen.PrimaryScreen.WorkingArea.Width * 15 / 200, Screen.PrimaryScreen.WorkingArea.Height * 15 / 200);
}

Be sure StartPosition is set to manual.

I usually attempt to load an application with the same position and size it had when it last run, with this information persisted in the registry.

There are a few complications in trying to do this - the screen resolution may have changed since the app last ran, etc. To do so you might need to:

  • handle SizeChanged and remember the size of the form whenever its WindowState is Normal (no point in remembering it when it's maximized or minimized.

  • similarly remember its location whenever it's moved.

  • persist this information when the app is closed

  • on startup, use the persisted information to position and size the form, adjusted to ensure the whole form fits on the screen and has a sensible minimum size.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM