Click here to Skip to main content
Click here to Skip to main content

Tagged as

Save and restore your form size and location

, 11 Feb 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
It's one of those things that annoys me - and probably you - you set up five or so windows so they are in the right place on your desktop, and it lovely. Then you open them again tomorrow...and one of them always opens too big, and in the middle of the screen...

Introduction

It's really not difficult to save and restore your form size and position - all it takes is a few lines of code - but it's so easy to forget or not bother, and it does make a difference to how "professional" your application appears. And it can frustrate users who are trying to organise their desktop around the tasks that they actually do if that organisation is broken by having to move a app back to the place it belongs... 

So if it's that easy, why aren't you doing it? 

Using the code

There are only three things you need to do:

  1. Create a place to keep the size and location information
  2. Restore the information on start up
  3. Save the  information on close

Places to save location and size info 

The  easiest place to save this is in the  Application config file:

  • In Visual Studio, open your project branch in the Solution Explorer.
  • Open the  "Properties" sub-branch, and double click on the "Settings.Settings" leaf.
  • This will open the Project Settings page. Add a new Name entry: "InitialLocation" - leave it as "string" and "User" (you could enter a "Value", but it really isn't needed). 
  • Save and close the page.  

Restore location and size 

This is also easy  to do - the only thing you have to do is to set a Form property, or the display will look a bit messy when it opens. In the Visual Studio designer, set your Form StartPosition to Manual. If  you forget this, Windows will locate your form in it's idea of a good place, and then it will move to your selected location.

Then all you need to do is the code for restore. Handle the Form.Load event:  

private void frmMain_Load(object sender, EventArgs e)
    {
    if ((ModifierKeys & Keys.Shift) == 0)
        {
        string initLocation = Properties.Settings.Default.InitialLocation;
        Point il = new Point(0, 0);
        Size sz = Size;
        if (!string.IsNullOrWhiteSpace(initLocation))
            {
            string[] parts = initLocation.Split(',');
            if (parts.Length >= 2)
                {
                il = new Point(int.Parse(parts[0]), int.Parse(parts[1]));
                }
            if (parts.Length >= 4)
                {
                sz = new Size(int.Parse(parts[2]), int.Parse(parts[3]));
                }
            }
        Size = sz;
        Location = il;
        }
    }

The conditional just allows your users to override the re-locate: if they hold the SHIFT key down while opening your application, it will ignore the saved location and size info, and appear at the top left in the default size you specify in the designer.  This allows them to recover if they manage to lose it completely!

All this does is read the settings, do a basic check that they are OK and splits them into separate values. If there are enough values for a location, it sets one. If there are also enough values for a size, it sets that too. It does not check to make sure the values are integers -  if they aren't then your program is almost certainly responsible, because you have saved duff info!

If you didn't set a  "Value" in the "Settings" page, it will fail the basic check, and the location and size will not be changed the first time the application runs - it will appear at the  top left corner in the size you set in the designer.  

Saving location and size  

All that remains is to save the info when the application  closes. Again, this is simple, just handle the FormClosing event:

private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
    {
    if ((ModifierKeys & Keys.Shift) == 0)
        {
        Point location = Location;
        Size size = Size;
        if (WindowState != FormWindowState.Normal)
            {
            location = RestoreBounds.Location;
            size = RestoreBounds.Size;
            }
        string initLocation = string.Join(",", location.X, location.Y, size.Width, size.Height);
        Properties.Settings.Default.InitialLocation = initLocation;
        Properties.Settings.Default.Save();
        }
    }

Again, this provides an override for the user to not save the information by holding down the SHIFT key when they close your application.  

Points of Interest 

That's it - all done. The only thing to remember is that the Applications settings file is different for Debug and Release versions - so don't expect the settings to transfer when you switch the build type!

History

  • 2013-02-10: First version.
  • 2013-02-11: Added support for minimized and maximized forms (My thanks to Alan N[^] for suggesting this)
  • 2013-02-11: Typos (spelling mostly, nothing serious) 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

OriginalGriff
CEO
Wales Wales
Born at an early age, he grew older. At the same time, his hair grew longer, and was tied up behind his head.
Has problems spelling the word "the".
Invented the portable cat-flap.
Currently, has not died yet. Or has he?
Follow on   Google+

Comments and Discussions

 
NewsUsing Extension Methods really worked out well PinmemberTennChris24-Oct-13 16:54 
BugNo edge cases Pinmemberjeffb4221-Feb-13 10:22 
GeneralMy vote of 5 PinmemberCHill6013-Feb-13 3:21 
QuestionOH MY.... Pinmembercodeeer@qq.com13-Feb-13 3:08 
GeneralThoughts PinmemberPIEBALDconsult11-Feb-13 14:07 
AnswerRe: Thoughts Pinmemberjeffb4221-Feb-13 10:26 
GeneralRe: Thoughts PinmemberPIEBALDconsult21-Feb-13 14:10 
AnswerRe: Thoughts [modified] Pinmemberjeffb4221-Feb-13 17:33 
QuestionMy vote 5 PinmemberJibesh11-Feb-13 9:55 
GeneralMy vote of 5 PinmvpMarcus Kramer11-Feb-13 5:27 
QuestionAn enhancement PinmemberAlan N10-Feb-13 8:52 
One useful tweak would be to check the WindowState before saving. If Maximized or Minimized then use the RestoreBounds in preference to the straight Size and Location properties.
 
From the data below you can see that the Minimized location is somewhere in next door's cellar and you definitely wouldn't want to restore your window down there.
The data also is slightly misleading as it suggests that RestoreBounds could always be used but really it is valid only when not Normal.
 
WindowState Normal
Size {Width=666, Height=318}
Location {X=703,Y=101}
RestoreBounds.Size {Width=666, Height=318}
RestoreBounds.Location {X=703,Y=101}
 
WindowState Minimized
Size {Width=160, Height=33}
Location {X=-32000,Y=-32000}
RestoreBounds.Size {Width=666, Height=318}
RestoreBounds.Location {X=703,Y=101}
 
WindowState Maximized
Size {Width=1410, Height=1022}
Location {X=-5,Y=-5}
RestoreBounds.Size {Width=666, Height=318}
RestoreBounds.Location {X=703,Y=101}
Alan.
AnswerRe: An enhancement PinmvpOriginalGriff11-Feb-13 4:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.141022.2 | Last Updated 11 Feb 2013
Article Copyright 2013 by OriginalGriff
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid