当用户将主窗体拖到第二个屏幕时,子窗体在第一个屏幕上打开

Child form opens on first screen when user has dragged the main form to the second screen

我的应用程序的主窗体在启动时会在笔记本电脑(主屏幕)上打开。然后用户将它拖到另一个屏幕(用于大显示器),并打开一个显示在笔记本电脑屏幕上的子窗体,而不是应用程序的主窗体(大显示器)。我希望子窗体在当前打开应用程序主窗体的屏幕上打开。

我尝试了以下选项,但它们只在调试模式下有效,在生产模式下无效

ChildForm.ShowDialog((IWin32Window)this.MainForm);
ChildForm.ShowDialog(formMainInstance);
ChildForm.Show(formMainInstance);

我知道 FormStartPosition.CenterParent,但这对我来说不是正确的选择。我该怎么做?

据我所知,您有 3 个选择:

  1. 使用FormStartPosition.CenterScreen;

         private void button2_Click(object sender, EventArgs e)
     {          
         Form2 child = new Form2();
         child.StartPosition = FormStartPosition.CenterScreen;
         child.ShowDialog(this);
     }
    
  2. 使用FormStartPosition.CenterParent

    private void button2_Click(object sender, EventArgs e)
     {          
         Form2 child = new Form2();
         child.StartPosition = FormStartPosition.CenterParent;
         child.ShowDialog(this);
     }
    

    }

  3. 使用FormStartPosition.Manual并传一个点

        private void button2_Click(object sender, EventArgs e)
     {          
         Form2 child = new Form2();
         child.StartPosition = FormStartPosition.Manual;
         child.Location = new System.Drawing.Point(0, 0);
         child.ShowDialog(this);
     }
    

以下代码对我有用。

var screen = Screen.FromControl(childFormInstance);
var MainFormScreen = Screen.FromControl(_formMainInstance);
ChildForm.Left = MainFormScreen.WorkingArea.Left + 120;
ChildForm.Top = MainFormScreen.WorkingArea.Top + 120;
ChildForm.ShowDialog();
  1. 首先查询子窗体要打开哪个屏幕
  2. 然后我查询我的主窗体当前打开的是哪个屏幕
  3. 然后我覆盖子窗体屏幕