【问题标题】:How to save and use app's window size?如何保存和使用应用程序的窗口大小?
【发布时间】:2012-02-03 19:37:03
【问题描述】:

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

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

谢谢。

【问题讨论】:

  • 是的,所有非 Web .NET 项目都可以使用配置文件,通常命名为 app.config
  • 如果您在寻找 WPF 解决方案,为什么这个标记为 winforms?

标签: c# wpf windows winforms


【解决方案1】:

我知道很久以前就已经回答了,但是,这是我在互联网上搜索两天后找到的最优雅的解决方案。看看这个:

http://blogs.msdn.com/b/davidrickard/archive/2010/03/09/saving-window-size-and-location-in-wpf-and-winforms.aspx

它也适用于 WPF 和 WinForms。

【讨论】:

    【解决方案2】:

    说明

    Windows 窗体

    • 在应用程序设置中创建属性 LocationXLocationYWindowWidthWindowHeight(类型为 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();
    }
    

    更多信息

    WPF

    • 在应用程序设置中创建属性 LocationXLocationYWindowWidthWindowHeight(类型为 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();
    }
    

    更多信息

    我已经测试过 WinForms 和 WPF。

    【讨论】:

    • 我建议在加载的处理程序中添加一个检查,以查看宽度或高度是否为 0 或小于某个小数字。
    • 如果您最大化应用程序,这样会保存全屏大小,因此不会保存常规窗口大小。最好看看这个答案:stackoverflow.com/a/30165932/9758687
    【解决方案3】:

    如果你打算只保存一个窗口positionsize,我建议将它们保存在applicationSettings中。

    如果您需要保存更多窗口设置,或者需要管理更多窗口,个人建议将其保存在单独的XML 文件中。

    编辑

    Working with XML standart way example

    LINQ to XML example

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-23
      • 2012-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多