首页 > Windows开发 > 详细

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

时间:2019-04-18 13:00:35      阅读:176      评论:0      收藏:0      [点我收藏+]
原文: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指定窗口的起始位置

?

?

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

原文:https://www.cnblogs.com/lonelyxmas/p/10728803.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!