如何保存和使用应用程序的窗口大小?

use*_*676 4 c# windows wpf winforms

使用.NET 4,在关闭时保存应用程序窗口大小和位置的最佳方法是什么,并在下次运行时使用这些值启动应用程序窗口?

我不想触摸任何类型的注册表,但不知道是否有某种app.config(类似于ASP.NET应用程序的web.config),我可以用于Windows Presentation Foundation应用程序.

谢谢.

dkn*_*ack 10

描述

Windows窗体

  • 在应用程序设置LocationX,LocationY,WindowWidth,WindowHeight (类型为int)中创建属性
  • 保存位置和大小 Form_FormClosed
  • 加载并应用位置和大小 Form_Load

样品

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();
}
Run Code Online (Sandbox Code Playgroud)

更多信息

WPF

  • 在应用程序设置LocationX,LocationY,WindowWidth,WindowHeight(double类型)中创建属性
  • 保存位置和大小 MainWindow_Closed
  • 加载并应用位置和大小 MainWindow_Loaded

样品

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();
}
Run Code Online (Sandbox Code Playgroud)

更多信息

我测试了WinForms和WPF.