WPF编程,窗口保持上次关闭时的大小与位置。

原文: WPF编程,窗口保持上次关闭时的大小与位置。

版权声明:我不生产代码,我只是代码的搬运工。 https://blog.csdn.net/qq_43307934/article/details/87971342

1、双击Settings.settings文件 

2、增加变量

向资源中添加两个变量MainRestoreBounds和MainWindowState,对应类型如图所示,用于保存主窗口的RestoreBounds属性值。 

此处第一行的数值是初始值,具体根据屏幕、窗口大小而定 

3、 XAML增加窗口关闭事件

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="360" Height="240"
        Closing="Window_Closing">
</Window>

4、后台对应的窗口关闭事件

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            //保存当前位置、大小和状态,到配置文件
            Properties.Settings.Default.MainRestoreBounds = this.RestoreBounds;
            Properties.Settings.Default.MainWindowState = this.WindowState;
            Properties.Settings.Default.Save();
            
        }

5、在后台窗口的构造函数中执行

        public MainWindow()
        {
            InitializeComponent();
            
            //读取配置文件
            try
            {
                //设置位置、大小
                Rect restoreBounds = Properties.Settings.Default.MainRestoreBounds;
                this.WindowState = WindowState.Normal;
                this.Left = restoreBounds.Left;
                this.Top = restoreBounds.Top;
                this.Width = restoreBounds.Width;
                this.Height = restoreBounds.Height;
                //设置窗口状态
                this.WindowState = Properties.Settings.Default.MainWindowState;
            }
            catch { }           
        }

注意:

如果需要窗口再打开时记住上次关闭时的状态,不要用WindowStartupLocation指定窗口的起始位置

猜你喜欢

转载自www.cnblogs.com/lonelyxmas/p/10728803.html
今日推荐