C# – .NET WPF Remember window size between sessions

cnetwindowswpf

Basically when user resizes my application's window I want application to be same size when application is re-opened again.

At first I though of handling SizeChanged event and save Height and Width, but I think there must be easier solution.

Pretty simple problem, but I can not find easy solution to it.

Best Answer

Save the values in the user.config file.

You'll need to create the value in the settings file - it should be in the Properties folder. Create five values:

  • Top of type double
  • Left of type double
  • Height of type double
  • Width of type double
  • Maximized of type bool - to hold whether the window is maximized or not. If you want to store more information then a different type or structure will be needed.

Initialise the first two to 0 and the second two to the default size of your application, and the last one to false.

Create a Window_OnSourceInitialized event handler and add the following:

this.Top = Properties.Settings.Default.Top;
this.Left = Properties.Settings.Default.Left;
this.Height = Properties.Settings.Default.Height;
this.Width = Properties.Settings.Default.Width;
// Very quick and dirty - but it does the job
if (Properties.Settings.Default.Maximized)
{
    WindowState = WindowState.Maximized;
}

NOTE: The set window placement needs to go in the on source initialised event of the window not the constructor, otherwise if you have the window maximised on a second monitor, it will always restart maximised on the primary monitor and you won't be able to access it.

Create a Window_Closing event handler and add the following:

if (WindowState == WindowState.Maximized)
{
    // Use the RestoreBounds as the current values will be 0, 0 and the size of the screen
    Properties.Settings.Default.Top = RestoreBounds.Top;
    Properties.Settings.Default.Left = RestoreBounds.Left;
    Properties.Settings.Default.Height = RestoreBounds.Height;
    Properties.Settings.Default.Width = RestoreBounds.Width;
    Properties.Settings.Default.Maximized = true;
}
else
{
    Properties.Settings.Default.Top = this.Top;
    Properties.Settings.Default.Left = this.Left;
    Properties.Settings.Default.Height = this.Height;
    Properties.Settings.Default.Width = this.Width;
    Properties.Settings.Default.Maximized = false;
}

Properties.Settings.Default.Save();

This will fail if the user makes the display area smaller - either by disconnecting a screen or changing the screen resolution - while the application is closed so you should add a check that the desired location and size is still valid before applying the values.