Click here to Skip to main content
Click here to Skip to main content
Go to top

Painless Persistence of Windows Forms Positions

, 21 May 2008
Rate this:
Please Sign up or sign in to vote.
A no-pain way of retaining your Windows Form positions between application runs.

Introduction

This is a simple drop-in component that will retain the bounds and state of a window between sessions of an application.

Background

A common task in developing desktop applications is remembering where the user put their forms in the last application run. Some users spend a great deal of time setting up their workspace exactly right, and it is quite an unpleasant experience to realise the application doesn't remember their hard work.

Using the Code

To use the code, follow these steps:

  1. Simply add a reference to the RememberFormPosition assembly, or include the source in your own project
  2. Open the designer for your Windows Form of choice
  3. From the toolbox, add a RememberFormPosition component

And that is all there is to it.

Points of Interest

Where Data is Stored

The position and state information for each form is stored in the Registry in the Application.UserAppDataRegistry key. The following Registry entries will be created:

  • FormName_Left
  • FormName_Top
  • FormName_Right
  • FormName_Bottom
  • FormName_State

Where FormName is the name of the form or the custom name that is provided to the control.

When the Data is Read in

The RememberFormPosition component implements the ISupportInitialize interface, and we do the reading of the form state in the EndInit() implementation.

Doing this in EndEdit() ensures that

  • The form is not yet visible, so no update flickering can take place. For example, if we did this on the FormLoad event instead, we would see the window move around as it has already been made visible.
  • The Form property of the RememberFormPosition component is set up.
public void EndInit()
{
  _form.StartPosition = FormStartPosition.Manual;
  RememberFormPositionUtils.RestoreFormPlacement(Application.UserAppDataRegistry,
                                                Form,
                                                UseFormName ? _form.Name : StorageName);
}

When is the Information Written

During the initialization of the RememberFormPosition component, we attach an event handler to our form's FormClosing event. During this, we write out the form's position and state. This is done because it ensures the form has not been disposed yet and all the information we need is in a valid state.

How are Minimized and Maximized Windows Handled

The special cases of a form being maximized or minimized needs to be handled carefully, because using the ordinary Control.Bounds will not achieve the desired result. In the case of being maximized, it will be the extends of the current Screen.WorkingArea, and in the case of minimized, it may be very small and will not be useful.

So when our Form.WindowState is not FormWindowState.Normal, we do the following:

  • Look at the Form.RestoreBounds property
  • This Form.RestoreBounds property is relative to Screen.PrimaryScreen.WorkingArea, so we need to compute the desktop bounds for this
  • We then write out the current WindowState

The function that handles this is RemeberFormPositionUtils.SaveFormPlacement().

public static void SaveFormPlacement(RegistryKey key, Form form, string name)
{
  if (form.WindowState == FormWindowState.Normal)
  {
    key.SetRectangleValue(name, form.DesktopBounds);
  }
  else
  {
    Rectangle workingArea = Screen.PrimaryScreen.WorkingArea;
    Rectangle restoreBounds = form.RestoreBounds;
    restoreBounds.X -= workingArea.X;
    restoreBounds.Y -= workingArea.Y;
    key.SetRectangleValue(name, restoreBounds);
  }
  key.SetWindowStateValue(name, form.WindowState);
}

When reading these back in, we:

  • Set Form.StartPosition to FormStartPosition.Manual
  • Set the WindowState to FormWindowState.Normal
  • We then set form bounds by using Form.SetDesktopBounds()
  • After this, we change Form.WindowState to the state stored in the Registry

The code that handles this is primarily in RemeberFormPositionUtils.RestoreFormPlacement().

public static void RestoreFormPlacement(RegistryKey key, Form form, string name)
{
  Rectangle? rect = key.GetRectangleValue(name);

  if (rect.HasValue)
  {
    Rectangle formBounds = rect.Value;

    if (!form.IsMdiChild)
    {
      formBounds = EnsureFitsInDesktop(formBounds);
    }

    form.WindowState = FormWindowState.Normal;
    form.SetDesktopBounds(formBounds.X, formBounds.Y, 
                          formBounds.Width, formBounds.Height);
  }

  FormWindowState? state = key.GetWindowStateValue(name);

  if (state.HasValue)
  {
    form.WindowState = state.Value;
  }
}

Extension Methods

A small portion of the code makes use of Extension Methods to read and write values from the Registry. It is hardly a necessary thing, but it was just something to experiment with.

If you wish to use the code in a C# 2.0 compiler, it should be a trivial task to remove the extra this keywords and just refer to the static classes explicitly.

Multiple Monitors

Multiple monitors has not been tested, but preliminary code has been put in place to handle it. If all four corners of the form are out of an available Screen, then we place the form in the middle of the screen. Also, if the form is too big to fit on the screen, we resize it so it is just under the size of the working area.

Things Learned About Components and WinForms in General

Designer Serialized Properties

When exposing properties that are [Browsable(true)], ensure that if you have a [DefaultValue] attribute, you also set up this default value in your constructor! If you do not, then if these conditions are true:

  • Your property value is the same as your DefaultValue.
  • Your DefaultValue is different from the default compiler value.

Then your property value will not get serialized and it will very confusingly lose your value. This happens because in designer serialized code, if a property value equals a DefaultValue, then the value is not written out as part of serialization. And hence next time the designer appears and your object is instantiated, it will revert to the compiler generated value.

Discovering the Owner of a Component

This was not as straightforward a task as I would have imagined. Components to not have direct knowledge of the Component or Control they are a part of.

In order to achieve this, a simple ComponentDesigner needed to be created in order to initialise our RememberFormPosition.Form property to the current Form. Inside ComponentDesigner.Initialize(), we have the ability to enquire what component we are designing via the ComponentDesigner.ParentComponent property.

History

  • 21/05/2008 - First article version.

License

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

Share

About the Author

Phil Martin
Software Developer (Senior) MineSched Software International
Canada Canada
A professional developer in the Mining sector since 2001, Phil has a passion for creating robust, quality scientific applications.
 
My recent professional work focuses on scheduling and optimisation in the mining sector.
 
My major fields of interest in software are 3D applications, visualisation, scheduling and optimisation, and novel UI design. My goal as a professional developer is to help people solve real world problems through reliable and fun to use software.

Comments and Discussions

 
GeneralYet another congratulation message PinmemberTiago Freitas Leal13-May-09 5:07 
GeneralRe: Yet another congratulation message PinmemberPhil Martin...13-May-09 12:24 
GeneralRe: Yet another congratulation message PinmemberTiago Freitas Leal13-May-09 13:33 
GeneralRe: Yet another congratulation message PinmemberTiago Freitas Leal23-May-09 0:39 
GeneralChange of storage Pinmemberdactivo11-Nov-08 0:40 
GeneralRe: Change of storage PinmemberPhil Martin...11-Nov-08 9:55 
GeneralSuggestion PinmemberChantiPDM18-Jul-08 13:06 
GeneralInteresting subject PinmemberGrommel21-May-08 5:09 
GeneralRe: Interesting subject PinmemberPhil Martin...21-May-08 12:31 
RantRegistry in Vista PinmemberItay Sagui21-May-08 5:00 
GeneralRe: Registry in Vista PinmemberPhil Martin...21-May-08 12:30 
GeneralI have seen this done before PinmvpSacha Barber21-May-08 4:15 
GeneralRe: I have seen this done before PinmemberPhil Martin...21-May-08 12:29 
GeneralRe: I have seen this done before PinmvpSacha Barber21-May-08 21:11 
GeneralMissing download PinprotectorMarc Clifton21-May-08 2:47 
GeneralRe: Missing download PinmemberPhil Martin...21-May-08 3:55 
GeneralNo source code Pinmember leppie 21-May-08 2:47 
GeneralRe: No source code PinmemberPhil Martin...21-May-08 3:53 

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
Web03 | 2.8.140916.1 | Last Updated 21 May 2008
Article Copyright 2008 by Phil Martin
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid