如何确保在双监视器方案中"附加"监视器上显示表单?

Moh*_*san 20 c# multiple-monitors winforms

我有一个应用程序,其中有一个表单,我想在第二个屏幕上显示.

平均值如果应用程序在屏幕A上运行,当我单击菜单以显示表格时,它应显示在屏幕B上,如果应用程序在屏幕B上运行,当我单击菜单显示表格时,它应显示在屏幕A上.

SLa*_*aks 42

您需要使用Screen该类来查找原始表单未打开的屏幕,然后Location根据该屏幕设置第二个表单的属性Bounds.

例如:

var myScreen = Screen.FromControl(originalForm);
var otherScreen = Screen.AllScreens.FirstOrDefault(s => !s.Equals(myScreen)) 
               ?? myScreen;
otherForm.Left = otherScreen.WorkingArea.Left + 120;
otherForm.Top = otherScreen.WorkingArea.Top + 120;
Run Code Online (Sandbox Code Playgroud)

这适用于任意数量的屏幕.

请注意,视频卡可能配置为使Windows看到一个大屏幕而不是两个较小屏幕,在这种情况下,这变得更加困难.

  • 更多:_(s => s!= myScreen)_不起作用; 我不得不使用_(s =>!s.Equals(myScreen))_ (2认同)
  • 我必须设置 `otherForm.StartPosition = FormStartPosition.Manual` 才能正常工作。 (2认同)

Chr*_*ris 19

下面是一个允许您在任何监视器上显示表单的功能.对于您当前的场景,您可以调用它showOnMonitor(1);.

基本上,您必须从中获取屏幕信息Screen.AllScreens,然后获取每个屏幕的尺寸,然后将表单放在您需要的位置

function void showOnMonitor(int showOnMonitor) 
{ 
    Screen[] sc; 
    sc = Screen.AllScreens; 

    Form2 f = new Form2(); 

    f.FormBorderStyle = FormBorderStyle.None; 
    f.Left = sc[showOnMonitor].Bounds.Left; 
    f.Top = sc[showOnMonitor].Bounds.Top; 
    f.StartPosition = FormStartPosition.Manual; 

    f.Show(); 
}
Run Code Online (Sandbox Code Playgroud)

注意不要忘记进行验证以确保您实际上有两个屏幕等,否则将引发异常以进行访问 sc[showOnMonitor]

  • 它应该是f.Left = sc [showOnMonitor] .Bounds.Left; f.Top = sc [showOnMonitor] .Bounds.Top; (2认同)

Nap*_*Nap 12

在OnLoad方法上,更改窗口的位置.

protected void Form1_OnLoad(...) {
    showOnMonitor(1);
}

private void showOnMonitor(int showOnMonitor) 
{ 
    Screen[] sc; 
    sc = Screen.AllScreens; 
    if (showOnMonitor >= sc.Length) {
        showOnMonitor = 0;
    }

    this.StartPosition = FormStartPosition.Manual; 
    this.Location = new Point(sc[showOnMonitor].Bounds.Left, sc[showOnMonitor].Bounds.Top);
    // If you intend the form to be maximized, change it to normal then maximized.
    this.WindowState = FormWindowState.Normal;
    this.WindowState = FormWindowState.Maximized;
}
Run Code Online (Sandbox Code Playgroud)

  • 为什么不只是`this.Location = sc [showOnMonitor] .Bounds.Location`? (2认同)