Click here to Skip to main content
15,867,686 members
Articles / Desktop Programming / WPF

Save and Restore WPF Window Size, Position, and/or State

Rate me:
Please Sign up or sign in to vote.
4.88/5 (48 votes)
3 Aug 2012CPOL2 min read 193.6K   4.3K   68   44
A quick example of how you can save the window size, position, and/or state, and restore your form to that size, position, and state the next time the app is launched.

Introduction

A quick example of how you can save a window's size, position, and/or state, and restore to that size, position, and state the next time the app is launched.

Background

This started as part of a real world app where I wanted the user to be able to resize the window and not have the window return to the default size the next time the app was launched. Many of my users have two monitors, so I decided to let them choose which monitor to open the window on, but I also wanted to make sure it didn't open on their "second monitor" when they took their laptop home and had only one monitor.

Using the Code

The first thing I did was setup some user settings to hold the data I wanted to save.

Image 1

Then, I created a UserPreferences class to handle loading and saving of the settings. The class consists of a property (with backing variable) for each of the settings, and a few methods for loading, saving, and manipulating the settings.

Here are the methods for loading and saving the settings. Notice that when I save the settings, I don't save if the window state is minimized. I don't want my app to start minimized.

C#
private void Load()
{
    _windowTop = Properties.Settings.Default.WindowTop;
    _windowLeft = Properties.Settings.Default.WindowLeft;
    _windowHeight = Properties.Settings.Default.WindowHeight;
    _windowWidth = Properties.Settings.Default.WindowWidth;
    _windowState = Properties.Settings.Default.WindowState;
}

public void Save()
{
    if (_windowState != System.Windows.WindowState.Minimized)
    {
        Properties.Settings.Default.WindowTop = _windowTop;
        Properties.Settings.Default.WindowLeft = _windowLeft;
        Properties.Settings.Default.WindowHeight = _windowHeight;
        Properties.Settings.Default.WindowWidth = _windowWidth;
        Properties.Settings.Default.WindowState = _windowState;

        Properties.Settings.Default.Save();
    }
}

I then created a method to shrink the window down to fit in the current desktop, if needed.

C#
public void SizeToFit()
{
    if (_windowHeight > System.Windows.SystemParameters.VirtualScreenHeight)
    {
        _windowHeight = System.Windows.SystemParameters.VirtualScreenHeight;
    }

    if (_windowWidth > System.Windows.SystemParameters.VirtualScreenWidth)
    {
        _windowWidth = System.Windows.SystemParameters.VirtualScreenWidth;
    }
}

And lastly, I created a method that moves the window onto the desktop if it is more than half out of view. This is really important if you are going to save the position, because we don't want to restore the window to a position off the user's desktop.

C#
public void MoveIntoView()
{
    if (_windowTop + _windowHeight / 2 > 
         System.Windows.SystemParameters.VirtualScreenHeight)
    {
        _windowTop = 
          System.Windows.SystemParameters.VirtualScreenHeight - 
          _windowHeight;
    }

    if (_windowLeft + _windowWidth / 2 > 
             System.Windows.SystemParameters.VirtualScreenWidth)
    {
        _windowLeft = 
          System.Windows.SystemParameters.VirtualScreenWidth - 
          _windowWidth;
    }

    if (_windowTop < 0)
    {
        _windowTop = 0;
    } 
    
    if (_windowLeft < 0)
    {
        _windowLeft = 0;
    }
}

The constructor for the UserPreferences class calls Load(), SizeToFit(), and MoveIntoView().

C#
public UserPreferences()
{
    //Load the settings
    Load();

    //Size it to fit the current screen
    SizeToFit();

    //Move the window at least partially into view
    MoveIntoView();
}

Then, in the window you want to resize, we just load the settings into the window in the constructor, and save the settings on Window_Closing.

C#
public Window1()
{
    InitializeComponent();

    var userPrefs = new UserPreferences();

    this.Height = userPrefs.WindowHeight;
    this.Width = userPrefs.WindowWidth;
    this.Top = userPrefs.WindowTop;
    this.Left = userPrefs.WindowLeft;
    this.WindowState = userPrefs.WindowState;

}

private void Window_Closing(object sender, 
             System.ComponentModel.CancelEventArgs e)
{
    var userPrefs = new UserPreferences();

    userPrefs.WindowHeight = this.Height;
    userPrefs.WindowWidth = this.Width;
    userPrefs.WindowTop=this.Top ;
    userPrefs.WindowLeft = this.Left;
    userPrefs.WindowState = this.WindowState;
    
    userPrefs.Save();
}

Points of Interest

When I resized and repositioned my form, I didn't take into account the height of the Windows task bar, so if the user resizes the screen to a smaller screen, the bottom of my form may be hidden by the task bar.

History

  • 1/7/09 - Initial post.
  • 1/8/09 - Removed binding from window to UserPreferences to allow setting the window size at design time and to prevent binding from being removed if you resize the window using a designer.

License

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


Written By
Software Developer
United States United States
I’m a Software Engineer at Microsoft working on the Azure Portal. Before that I spent about 20 years developed various business applications at a number of different companies. I have a passion for writing clean, scalable code and sharing what I’ve learned with others.

I also help run the Casco Bay .Net User Group

Comments and Discussions

 
QuestionMicrosoft official sample Pin
Gabriel Kummer 202115-Jun-23 2:54
Gabriel Kummer 202115-Jun-23 2:54 
QuestionNot working on left screen Pin
Gabriel Kummer 202115-Jun-23 0:06
Gabriel Kummer 202115-Jun-23 0:06 
PraiseStill working Nov 2022 Pin
mikey80316-Nov-22 4:02
mikey80316-Nov-22 4:02 
Question2022 and still working Pin
Juan Pablo Jul20227-Jul-22 2:14
Juan Pablo Jul20227-Jul-22 2:14 
PraiseThank you very much. Pin
K. K. VinayKumar29-Jul-16 3:36
K. K. VinayKumar29-Jul-16 3:36 
GeneralMy vote of 5 Pin
Rollie2-Aug-15 4:32
Rollie2-Aug-15 4:32 
QuestionHaving an issue with Maximized windows Pin
melance4210-Dec-14 3:22
melance4210-Dec-14 3:22 
AnswerRe: Having an issue with Maximized windows Pin
Jeremy Hutchinson16-Dec-14 3:57
professionalJeremy Hutchinson16-Dec-14 3:57 
GeneralRe: Having an issue with Maximized windows Pin
tomscharf11-Jan-16 5:25
tomscharf11-Jan-16 5:25 
QuestionMoveIntoView isn't quite correct PinPopular
DougPotter16-Oct-13 13:25
DougPotter16-Oct-13 13:25 
GeneralThis Solution *way* better than Josh Smith's version - Vote of 5 Pin
MacSpudster16-Jul-13 6:38
professionalMacSpudster16-Jul-13 6:38 
GeneralRe: This Solution *way* better than Josh Smith's version - Vote of 5 Pin
MacSpudster16-Jul-13 6:41
professionalMacSpudster16-Jul-13 6:41 
GeneralMy vote of 4 Pin
Christian Amado3-Aug-12 5:29
professionalChristian Amado3-Aug-12 5:29 
BugMistype? Pin
AlexP1122328-Jul-12 8:05
AlexP1122328-Jul-12 8:05 
GeneralRe: Mistype? Pin
Jeremy Hutchinson3-Aug-12 6:02
professionalJeremy Hutchinson3-Aug-12 6:02 
QuestionMy vote of 5 too Pin
User 27100929-May-12 6:05
User 27100929-May-12 6:05 
GeneralMy vote of 5 Pin
User 27100929-May-12 6:04
User 27100929-May-12 6:04 
GeneralMy vote of 5 Pin
gpasupathi23-Aug-11 5:21
gpasupathi23-Aug-11 5:21 
QuestionAny chance of an update for it to work in an MVVM scenario? Pin
geoffhirst28-Jul-11 2:12
geoffhirst28-Jul-11 2:12 
Hi Jeremy,

It would be really great to see your take on how to implement this in an MVVM scenario.

thanks
Geoff Hirst
AnswerRe: Any chance of an update for it to work in an MVVM scenario? Pin
Jeremy Hutchinson28-Jul-11 2:17
professionalJeremy Hutchinson28-Jul-11 2:17 
AnswerRe: Any chance of an update for it to work in an MVVM scenario? Pin
appxdev9-Apr-12 18:06
appxdev9-Apr-12 18:06 
AnswerRe: Any chance of an update for it to work in an MVVM scenario? Pin
Erik Vullings28-Sep-12 4:19
Erik Vullings28-Sep-12 4:19 
GeneralGreat article, how would you extend it to multiple forms Pin
Dovan Rogars18-Mar-11 19:53
Dovan Rogars18-Mar-11 19:53 
GeneralRe: Great article, how would you extend it to multiple forms Pin
Jeremy Hutchinson21-Mar-11 2:33
professionalJeremy Hutchinson21-Mar-11 2:33 
GeneralBug with some dual screen configs.... Pin
Ybbozman6-Sep-10 22:44
Ybbozman6-Sep-10 22:44 

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.