记住 window 设置(大小、位置、位置)并恢复,但到屏幕 1

Remembering window settings (size, position, location) and restoring, but to screen 1

我有一个针对 .NET Framework 4.6.1 的 WinForms 应用程序。我需要在应用程序运行之间恢复所有表单的大小、位置和位置。这已经通过以下方式实现:

private void saveMainWindowSettings()
{
    Properties.Settings.Default.MainWindowState = this.WindowState;
    if (this.WindowState == System.Windows.Forms.FormWindowState.Normal)
    {
        // save location and size if state is normal
        Properties.Settings.Default.MainWindowLocation = this.Location;
        Properties.Settings.Default.MainWindowSize = this.Size;
    }
    else
    {
        // save the RestoreBounds if the form is maximised or minimised
        Properties.Settings.Default.MainWindowLocation = this.RestoreBounds.Location;
        Properties.Settings.Default.MainWindowSize = this.RestoreBounds.Size;
    }

    // save the main window settings
    Properties.Settings.Default.Save();
}

private void loadMainWindowSettings()
{
    if (Properties.Settings.Default.MainWindowSize.Width == 0 || Properties.Settings.Default.MainWindowSize.Height == 0)
    {
        // first start
        // add default values (size 912x598)
        this.Size = new System.Drawing.Size(912, 598);
    }
    else
    {
         // load the remembered settings

         this.WindowState = Properties.Settings.Default.MainWindowState;

         // we don't want a minimised window at startup
         if (this.WindowState == System.Windows.Forms.FormWindowState.Minimized)
                    this.WindowState = System.Windows.Forms.FormWindowState.Normal;

         this.Location = Properties.Settings.Default.MainWindowLocation;
         this.Size = Properties.Settings.Default.MainWindowSize;
     }
}

FormClosing事件处理器中调用了saveMainWindowSettings()方法,在Load事件处理器中调用了loadMainWindowSettings()方法。

但是,使用多台显示器时会出现问题。我已经在家里用一台笔记本电脑和一个额外的显示器测试了这段代码,它工作正常。但是,当使用不同的显示器进行测试时,window 在主屏幕(屏幕 1,笔记本电脑显示屏)上不可见,因为它在之前的设置中被拖到另一台显示器上。 window 是打开的,因为它在任务栏中可见,但根本看不到,也无法拖到主屏幕。看到它的唯一方法是在任务栏中右键单击它并最大化它。

为了避免这个问题,我想将 window 始终恢复到屏幕 1,以便它处于相同的状态(最小化、最大化、正常),以及相同的相对大小和位置,考虑分辨率的差异。如何实现?

我推测 "screen 1" 你的意思是 "primary display"。所有其他显示器都是次要的,当您 运行 您的应用程序时可能存在也可能不存在,并且如果存在,则在您保存设置时可能不是相同的显示,也可能在应用程序时处于相同的排列开始。

看看这个API:https://docs.microsoft.com/dotnet/api/system.windows.forms.screen.allscreens

你必须做几件事。

  1. 保存设置时,您必须将当前 window 坐标转换为主显示器上所需的坐标。这包括考虑当前显示器和主监视器(如果它们不同)的分辨率和比例因子。 例如。你的主显示器可以是 1920x1200 100% SF,你的辅助显示器可以是 2560x1440 125%。 在计算新坐标时,您需要确保新坐标不会在主监视器的可见区域之外结束。

  2. 当持久化信息以 100% SF 持久化时。

  3. 如果主监视器不在 100% SF,恢复时重新校准位置,并确保坐标在监视器的可见区域内(主监视器可能在应用 运行s).