首先先说窗口的可见性,Visibility,它有4个枚举值:
Visiable,可见;
Hidden,隐藏;
Collapsed,折叠。
虽然窗口类认为Collapsed与Hidden一样,但二者区别在于,Hidden仅仅将元素设为不可见,但是元素在画面上依然占有空间;而Collapsed,在不可视的基础上,能将元素在画面上的占位符清除,元素彻底不影响画面。
Show、Hide,显示窗口和隐藏窗口的两个方法。如果窗口的ShowInTaskbar属性值为true,Hide不但隐藏窗口本身,同时隐藏其在任务栏上的图标。
WindowState,窗口状态属性,有3个枚举值:
Normal,正常;
Maximized,最大化;
Minimized,最小化;
RestoreBounds,获取窗口在最小化或最大化之前的大小和位置,有4个枚举值,Top、Left、Width、Height。
//输出当前窗口的RestoreBounds值
private void button1_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show(this.RestoreBounds.ToString());
}
该主窗口的Top:75,Left:75,Width:525,Height:350
只有窗口在Normal状态下移动或调整时,RestoreBounds的值才会改变。于是可以在窗口关闭时将RestoreBounds属性值保存到配置文件,下一次启动程序窗口时,读取上次保存的窗口大小、位置,来初始化窗口,以此实现保存用户配置等功能。MSDN上的例子:http://msdn.microsoft.com/zh-cn/library/system.windows.window.restorebounds.aspx 。但推荐使用config文件来保存配置,更方便。
应用程序窗口在上次关闭处启动
向资源中添加两个变量MainRestoreBounds和MainWindowState,对应类型如图所示,用于保存主窗口的RestoreBounds属性值。
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>
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApplication1
{
public partial class MainWindow : Window
{
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 { }
}
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();
}
}
}