许多帖子都涉及恢复 WinForm 位置和大小。
例子:
- www.stackoverflow.com/questions/92540/save-and-restore-form-position-and-size http://www.stackoverflow.com/questions/92540/save-and-restore-form-position-and-size
但我还没有找到使用多个显示器执行此操作的代码。
也就是说,如果我关闭监视器 2 上窗口的 .NET Winform 应用程序,我希望它将窗口大小、位置和状态保存到应用程序设置中,以便稍后在我重新启动应用程序时恢复到监视器 2。如果像上面的 codeproject 示例一样,它包含一些健全性检查,就像保存的位置大部分在屏幕外一样,它会“修复”它,那就太好了。或者,如果保存的位置位于不再存在的显示器上(例如,我的笔记本电脑现在没有第二个显示器),那么它会正确地将其移动到显示器 1。
有什么想法吗?
我的环境:C#、.NET 3.5或以下、VS2008
试试这个代码。兴趣点:
- 检查窗口在任何屏幕的工作区域上是否(部分)可见。例如。将其拖动到任务栏后面或将其完全移出屏幕会将位置重置为 Windows 默认值。
- 即使表单最小化或最大化,也能保存正确的边界(常见错误)
- 正确保存 WindowState。根据设计禁用保存 FormWindowState.Minimized。
边界和状态以其相应的类型存储在应用程序设置中,因此不需要进行任何字符串解析。让框架发挥其序列化魔力。
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
// this is the default
this.WindowState = FormWindowState.Normal;
this.StartPosition = FormStartPosition.WindowsDefaultBounds;
// check if the saved bounds are nonzero and visible on any screen
if (Settings.Default.WindowPosition != Rectangle.Empty &&
IsVisibleOnAnyScreen(Settings.Default.WindowPosition))
{
// first set the bounds
this.StartPosition = FormStartPosition.Manual;
this.DesktopBounds = Settings.Default.WindowPosition;
// afterwards set the window state to the saved value (which could be Maximized)
this.WindowState = Settings.Default.WindowState;
}
else
{
// this resets the upper left corner of the window to windows standards
this.StartPosition = FormStartPosition.WindowsDefaultLocation;
// we can still apply the saved size
this.Size = Settings.Default.WindowPosition.Size;
}
}
private bool IsVisibleOnAnyScreen(Rectangle rect)
{
foreach (Screen screen in Screen.AllScreens)
{
if (screen.WorkingArea.IntersectsWith(rect))
{
return true;
}
}
return false;
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
// only save the WindowState if Normal or Maximized
switch (this.WindowState)
{
case FormWindowState.Normal:
case FormWindowState.Maximized:
Settings.Default.WindowState = this.WindowState;
break;
default:
Settings.Default.WindowState = FormWindowState.Normal;
break;
}
// reset window state to normal to get the correct bounds
// also make the form invisible to prevent distracting the user
this.Visible = false;
this.WindowState = FormWindowState.Normal;
Settings.Default.WindowPosition = this.DesktopBounds;
Settings.Default.Save();
}
}
参考设置文件:
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)" GeneratedClassNamespace="ScreenTest" GeneratedClassName="Settings">
<Profiles />
<Settings>
<Setting Name="WindowPosition" Type="System.Drawing.Rectangle" Scope="User">
<Value Profile="(Default)">0, 0, 0, 0</Value>
</Setting>
<Setting Name="WindowState" Type="System.Windows.Forms.FormWindowState" Scope="User">
<Value Profile="(Default)">Normal</Value>
</Setting>
</Settings>
</SettingsFile>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)