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

博客介绍了WPF窗口保存关闭状态和位置的方法。通过双击Settings.settings文件、增加MainRestoreBounds和MainWindowState变量保存窗口属性值,在XAML增加窗口关闭事件,编写后台对应事件,在构造函数中执行。还提醒若要记住上次关闭状态,勿用WindowStartupLocation指定起始位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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指定窗口的起始位置

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值