Click here to Skip to main content
15,867,704 members
Articles / Programming Languages / C#
Tip/Trick

Save and restore your form size and location

Rate me:
Please Sign up or sign in to vote.
4.98/5 (20 votes)
11 Feb 2013CPOL3 min read 69.5K   19   13
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). 
  • Image 1

  • 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:  

C#
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:

C#
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)


Written By
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?

Comments and Discussions

 
QuestionRevised version of extension methods Pin
Paul-Lastname28-Feb-18 18:41
Paul-Lastname28-Feb-18 18:41 
NewsUsing Extension Methods really worked out well Pin
TennChris24-Oct-13 16:54
TennChris24-Oct-13 16:54 
BugNo edge cases Pin
jeffb4221-Feb-13 10:22
jeffb4221-Feb-13 10:22 
GeneralMy vote of 5 Pin
CHill6013-Feb-13 3:21
mveCHill6013-Feb-13 3:21 
QuestionOH MY.... Pin
codeeer@qq.com13-Feb-13 3:08
codeeer@qq.com13-Feb-13 3:08 
GeneralThoughts Pin
PIEBALDconsult11-Feb-13 14:07
mvePIEBALDconsult11-Feb-13 14:07 
AnswerRe: Thoughts Pin
jeffb4221-Feb-13 10:26
jeffb4221-Feb-13 10:26 
GeneralRe: Thoughts Pin
PIEBALDconsult21-Feb-13 14:10
mvePIEBALDconsult21-Feb-13 14:10 
AnswerRe: Thoughts Pin
jeffb4221-Feb-13 17:33
jeffb4221-Feb-13 17:33 
QuestionMy vote 5 Pin
Jibesh11-Feb-13 9:55
professionalJibesh11-Feb-13 9:55 
GeneralMy vote of 5 Pin
fjdiewornncalwe11-Feb-13 5:27
professionalfjdiewornncalwe11-Feb-13 5:27 
QuestionAn enhancement Pin
Alan N10-Feb-13 8:52
Alan N10-Feb-13 8:52 
AnswerRe: An enhancement Pin
OriginalGriff11-Feb-13 4:49
mveOriginalGriff11-Feb-13 4:49 

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

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