基于David Veeneman的Code Project article on Windows Forms User Settings,我一直在努力保存应用程序的起始位置和起始大小。
它在单个实例中完美运行,但是当我将它扩展到多个实例时,我遇到了问题。
我已经处理了有关加载设置和将设置保存在互斥锁中的部分,以保护写入和设置文件的写入。
我希望窗口从最后一个已知位置堆叠。这似乎在大多数情况下工作得很好,但是如果我快速开始打开四五个窗口,前三个将完美打开,那么将有一个间隙,之后一些开始在同一位置打开。
呈现表单/应用程序:
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();
}
}
谁能告诉我我在做什么?或者如何基于上面的代码我可以将两个实例渲染到相同的起始位置?
由于 甲
答案 0 :(得分:1)
问题是在获取互斥锁之前加载了设置。获取互斥锁后调用Settings.Default.Reload()
。