基本上,当用户调整我的应用程序窗口大小时,我希望应用程序在再次重新打开时保持相同大小。
起初我想处理 SizeChanged 事件并保存高度和宽度,但我认为必须有更简单的解决方案。
非常简单的问题,但我找不到简单的解决方案。
最佳答案
将值保存在 user.config 文件中。
您需要在设置文件中创建值 - 它应该位于 Properties 文件夹中。创建五个值:
Top
类型double
Left
类型double
Height
类型double
宽度
double
Maximized
类型bool
- 保存窗口是否最大化。如果您想存储更多信息,则需要不同的类型或结构。
将前两个初始化为 0,将后两个初始化为应用程序的默认大小,将最后一个初始化为 false。
创建一个 Window_OnSourceInitialized 事件处理程序并添加以下内容:
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;
}
注意: 设置窗口位置需要进入窗口的源初始化事件而不是构造函数,否则如果您在第二台显示器上最大化窗口,它将始终重新启动最大化主监视器,您将无法访问它。
创建一个 Window_Closing 事件处理程序并添加以下内容:
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();
如果用户使显示区域变小 - 通过断开屏幕或更改屏幕分辨率 - 而应用程序关闭,这将失败,因此您应该在应用值之前添加检查以确保所需的位置和大小仍然有效.
关于c# - .NET WPF 记住 session 之间的窗口大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/847752/