Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save and use app's window size?

Using .NET 4, what is the best way to save an app's window size and position at closing and use these values to start the app's window next time it is run?

I prefer not to have to touch any kind of registry but don't know if there is some kind of app.config (similar to web.config for ASP.NET apps) that I can use for Windows Presentation Foundation apps.

Thanks.

like image 884
user776676 Avatar asked Dec 22 '22 03:12

user776676


2 Answers

Description

Windows Forms

  • Create Properties in Application Settings LocationX, LocationY, WindowWidth, WindowHeight (of type int)
  • Save Location and Size in Form_FormClosed
  • Load and apply Location and Size in Form_Load

Sample

private void Form1_Load(object sender, EventArgs e)
{
    this.Location = new Point(Properties.Settings.Default.LocationX, Properties.Settings.Default.LocationY);
    this.Width = Properties.Settings.Default.WindowWidth;
    this.Height = Properties.Settings.Default.WindowHeight;
}

private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
    Properties.Settings.Default.LocationX = this.Location.X;
    Properties.Settings.Default.LocationY = this.Location.Y;
    Properties.Settings.Default.WindowWidth = this.Width;
    Properties.Settings.Default.WindowHeight = this.Height;
    Properties.Settings.Default.Save();
}

More Information

  • Application Settings for Windows Forms
  • MSDN - Form.Load Event
  • MSDN - Form.Closed Event

WPF

  • Create Properties in Application Settings LocationX, LocationY, WindowWidth, WindowHeight (of type double)
  • Save Location and Size in MainWindow_Closed
  • Load and apply Location and Size in MainWindow_Loaded

Sample

void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
    this.Left = Properties.Settings.Default.LocationX;
    this.Top = Properties.Settings.Default.LocationY;
    this.Width = Properties.Settings.Default.WindowWidth;
    this.Height = Properties.Settings.Default.WindowHeight;
}

void MainWindow_Closed(object sender, EventArgs e)
{
    Properties.Settings.Default.LocationX = this.Left;
    Properties.Settings.Default.LocationY = this.Top;
    Properties.Settings.Default.WindowWidth = this.Width;
    Properties.Settings.Default.WindowHeight = this.Height;
    Properties.Settings.Default.Save();
}

More Information

  • Application Settings
  • MSDN - FrameworkElement.Loaded Event
  • MSDN - Window.Closed Event

I have tested both, WinForms and WPF.

like image 57
dknaack Avatar answered Dec 24 '22 00:12

dknaack


If you're going to save just one window position and size, I would suggest to save them in applicationSettings.

If you more window settings to save, or more windows to manage I would, personally suggest to save it in separate XML file.

EDIT

Working with XML standart way example

LINQ to XML example

Hope this helps.

like image 41
Tigran Avatar answered Dec 24 '22 02:12

Tigran