这似乎是一个标准要求:下次用户启动应用程序时,打开窗口的位置和状态与以前一样。这是我的愿望清单:
我将添加我目前的解决方案作为一个答案和限制。
发布于 2008-09-19 22:01:33
我的另一个选择是围绕应用程序设置编写更多自定义代码,并在formLoad和formClosed上执行。这不使用数据绑定。
缺点:
现在,这是我最喜欢的解决方案,但似乎工作量太大了。为了减少工作量,我创建了一个WindowSettings类,它将窗口位置、大小、状态和任何拆分器位置序列化为单个应用程序设置。然后,我可以为我的应用程序中的每个表单创建一个该类型的设置,在关闭时保存,并在加载时恢复。
我发布了源代码,包括WindowSettings类和一些使用它的表单。有关将其添加到项目的说明包含在WindowSettings.cs文件中。最棘手的部分是弄清楚如何添加具有自定义类型的应用程序设置。你选择浏览..。从类型下拉列表中,然后手动输入名称空间和类名。项目中的类型不会出现在列表中。
更新:我添加了一些静态方法来简化添加到每个表单中的样板代码。完成了向项目添加WindowSettings类和创建应用程序设置的说明之后,下面是一个代码示例,该代码必须添加到要记录和还原的每个表单中。
private void MyForm_FormClosing(object sender, FormClosingEventArgs e)
{
Settings.Default.CustomWindowSettings = WindowSettings.Record(
Settings.Default.CustomWindowSettings,
this,
splitContainer1);
}
private void MyForm_Load(object sender, EventArgs e)
{
WindowSettings.Restore(
Settings.Default.CustomWindowSettings,
this,
splitContainer1);
}
发布于 2008-09-20 13:58:36
下面的示例显示了我是如何做到的。
显然,这可以适应于持久化开始位置,以及关闭时是否最小化了表单--我不需要这样做。窗体上控件的其他设置(如拆分器位置和选项卡容器)非常简单。
private void FitToScreen()
{
if (this.Width > Screen.PrimaryScreen.WorkingArea.Width)
{
this.Width = Screen.PrimaryScreen.WorkingArea.Width;
}
if (this.Height > Screen.PrimaryScreen.WorkingArea.Height)
{
this.Height = Screen.PrimaryScreen.WorkingArea.Height;
}
}
private void LoadPreferences()
{
// Called from Form.OnLoad
// Remember the initial window state and set it to Normal before sizing the form
FormWindowState initialWindowState = this.WindowState;
this.WindowState = FormWindowState.Normal;
this.Size = UserPreferencesManager.LoadSetting("_Size", this.Size);
_currentFormSize = Size;
// Fit to the current screen size in case the screen resolution
// has changed since the size was last persisted.
FitToScreen();
bool isMaximized = UserPreferencesManager.LoadSetting("_Max", initialWindowState == FormWindowState.Maximized);
WindowState = isMaximized ? FormWindowState.Maximized : FormWindowState.Normal;
}
private void SavePreferences()
{
// Called from Form.OnClosed
UserPreferencesManager.SaveSetting("_Size", _currentFormSize);
UserPreferencesManager.SaveSetting("_Max", this.WindowState == FormWindowState.Maximized);
... save other settings
}
X
发布于 2008-09-19 21:54:27
我找到的最简单的解决方案是将数据绑定到应用程序设置中。我绑定窗口上的位置和clientSize属性以及拆分器上的splitterDistance。
缺点:
如果你想尝试这种奇怪的行为,我用这种技术发布了一个样品溶液。
https://stackoverflow.com/questions/105932
复制相似问题