.NET WPF记住会话之间窗口大小大小、窗口、NET、WPF

2023-09-02 10:53:52 作者:未署名情书

基本上,当用户改变我的应用程序的窗口,我想申请成为应用程序时再次重新打开相同的尺寸。

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

起初我处理SizeChanged事件和保存的高度和宽度,但我想一定有更简单的解决方案。虽然

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

pretty的简单的问题,但我不能找到简单的解决方案吧。

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

推荐答案

保存值在user.config文件。

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.

初​​始化前两个为0,第二个两到应用程序的默认大小,和最后一个虚假的。

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

在构造函数中:

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.Maximised)
{
    WindowState = WindowState.Maximized;
}

创建WINDOW_CLOSING事件处理程序,并添加以下内容:

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.Maximised = 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.Maximised = false;
}

Properties.Settings.Default.Save();

这将如果用户在失败的显示区域小 - 无论是通过断开屏幕或改变屏幕分辨率 - 当应用程序被关闭,所以你应该添加一个检查所需的位置和大小仍是应用之前有效值。

This will fail in 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.