根据David Veeneman关于 Windows 窗体用户设置的代码项目文章,我一直在尝试保存应用程序的开始位置和开始大小。
它在单个实例中完美运行,但是当我将其扩展到多个实例时,我遇到了问题。
我已经包装了处理加载设置并将设置保存在互斥锁中的部分,以保护对设置文件的写入和写入。
我希望窗户从最后一个已知位置开始堆叠。这在大多数情况下似乎工作正常,但如果我快速连续打开四五个窗口,前三个将完美打开,然后会有一个间隙,然后其中一些开始在同一位置打开。
呈现表单/应用程序:
private Mutex saveSetting;
private const int START_LOCATION_OFFSET = 20;
private void MainForm_Load(object sender, EventArgs e)
{
// Get the mutex before the reading of the location
// so that you can't have a situation where a window drawn
// in the incorrect position.
this.saveSetting = new Mutex(false, "SaveSetting");
this.saveSetting.WaitOne();
this.LoadWindowStartSizeAndLocation();
.
.
.
.
.
this.saveSetting.ReleaseMutex();
}
加载设置:
private void LoadWindowStartSizeAndLocation()
{
// Set window location
if (Settings.Default.WindowLocation != null)
{
System.Drawing.Point startLocation =
new System.Drawing.Point
(Settings.Default.WindowLocation.X + START_LOCATION_OFFSET,
Settings.Default.WindowLocation.Y + START_LOCATION_OFFSET);
this.Location = startLocation;
Settings.Default.WindowLocation = startLocation;
Settings.Default.Save();
}
// Set window size
if (Settings.Default.WindowSize != null)
{
this.Size = Settings.Default.WindowSize;
}
}
保存设置:
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
try
{
this.SaveWindowSizeAndLocationForNextStart();
}
catch (Exception ex)
{
System.Diagnostics.Debug.Assert(false, ex.Message);
}
}
/// <summary>
/// Save the Window Size And Location For the next Application Start up.
/// </summary>
private void SaveWindowSizeAndLocationForNextStart()
{
if (this.WindowState != FormWindowState.Minimized)
{
// Copy window location to app settings
Settings.Default.WindowLocation = this.Location;
Settings.Default.WindowSize = this.Size;
}
try
{
this.saveSetting = new Mutex(false, "SaveSetting");
this.saveSetting.WaitOne();
Settings.Default.Save();
}
catch
{
// Do nothing. It won't permanently disable the system if we
// can't save the settings.
}
finally
{
this.saveSetting.ReleaseMutex();
}
}
谁能告诉我我在做什么?或者如何根据上面的代码将两个实例渲染到同一个起始位置?
谢谢