我有一个C#应用程序,它在关闭时保存其状态,然后在启动时读取保存的状态.保存的一个项目是主窗体的位置.通常情况下这很好 - 在我的代码中有一行这样的行将位置保存到文件中,然后在启动时读回:
streamWriter.WriteLine("location:" + this.Location.X + "," + this.Location.Y);
Run Code Online (Sandbox Code Playgroud)
通常,我的机器上的位置坐标看起来像这样,有多个显示器:
location:-1069,283
Run Code Online (Sandbox Code Playgroud)
偶尔我会看到像这样保存的坐标:
location:-32000,-32000
Run Code Online (Sandbox Code Playgroud)
然后,当用户重新启动应用程序时,表单离桌面很远,并且普通用户无法(轻松)检索到该表单.
如何以这种方式读取坐标并且是否有建议来防止这种情况?
您看到的坐标是由于应用程序在关闭时被最小化的事实.Windows通过实际将其从坐标移动到一些非常大的负X,Y坐标来"隐藏"您的表单.
以编程方式验证:
来自Vista上的表单应用程序的输出:
当前坐标X:184 Y:184*默认位置当前坐标X: - 32000 Y: - 32000*最小化位置
从代码:
System.Diagnostics.Debug.WriteLine("当前坐标X:"+ Location.X +"Y:"+ Location.Y);
要解决这个问题,我只需在您的应用关闭时检查这样的值,而不是实际将其保存到文件中.
如果您不想在任意坐标值上进行数学操作,您还可以检查WindowState.在MSDN上看到这里
在您的表单上使用 RestoreBounds 属性。
编辑:这是我的一些代码的复制/粘贴(可能会使用一些清理,但它得到了重点)。这是来自我的主表单的 FormClosing 事件处理程序:
// Save the last form state
Program.AppSettings.MainWindowFormState = this.WindowState;
// Check if the window is minimized or maximized
if ((this.WindowState == FormWindowState.Minimized) ||
(this.WindowState == FormWindowState.Maximized))
{
// Use the restored state values
Program.AppSettings.MainWindowX = this.RestoreBounds.Left;
Program.AppSettings.MainWindowY = this.RestoreBounds.Top;
Program.AppSettings.MainWindowWidth = this.RestoreBounds.Width;
Program.AppSettings.MainWindowHeight = this.RestoreBounds.Height;
}
else
{
// Use the normal state values
Program.AppSettings.MainWindowX = this.Left;
Program.AppSettings.MainWindowY = this.Top;
Program.AppSettings.MainWindowWidth = this.Width;
Program.AppSettings.MainWindowHeight = this.Height;
}Run Code Online (Sandbox Code Playgroud)
以下是如何在加载时恢复状态(记住将表单的初始位置模式设置为手动以避免闪烁):
// Set the initial form state
this.WindowState = Program.AppSettings.MainWindowFormState;
this.Left = Program.AppSettings.MainWindowX;
this.Top = Program.AppSettings.MainWindowY;
this.Width = Program.AppSettings.MainWindowWidth;
this.Height = Program.AppSettings.MainWindowHeight;Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2593 次 |
| 最近记录: |