Mutex在加载Form设置时未按预期运行

本文关键字:运行 加载 Form 设置 Mutex | 更新日期: 2023-09-27 17:58:21

根据David Veeneman关于Windows窗体用户设置的Code Project文章,我一直在尝试保存应用程序的开始位置和开始大小。

它在单个实例中工作得很好,但当我将它扩展到多个实例时,我会遇到问题。

我已经完成了处理加载设置和将设置保存在互斥对象中的部分,以保护对设置文件的写入和从设置文件中的写入。

我希望窗口从最后一个已知的位置开始堆叠。大多数情况下,这似乎都很好,但如果我快速打开四五个窗户,前三个会完美打开,然后会有一个缺口,然后其中一些窗户开始在同一位置打开。

提交表单/应用程序:

 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();
        }
    }

有人能告诉我今天在做什么吗?或者,根据上面的代码,我如何将两个实例渲染到相同的起始位置??

谢谢

Mutex在加载Form设置时未按预期运行

问题是在获取互斥之前加载设置。获取互斥后调用Settings.Default.Reload()