2

我有双显示器并希望在屏幕中央显示一个窗口窗体。(我有一个变量 MonitorId=0 或 1)。

我有:

System.Windows.Forms.Screen[] allScreens=System.Windows.Forms.Screen.AllScreens;
System.Windows.Forms.Screen myScreen = allScreens[0];

int screenId = RegistryManager.ScreenId;
// DualScreen management
if (screenId > 0)
{
    // has 2nd screen
    if (allScreens.Length == 2)
    {
        if (screenId == 1)
            myScreen = allScreens[0];
        else
            myScreen = allScreens[1];
    }
}

this.Location = new System.Drawing.Point(myScreen.Bounds.Left, 0);
this.StartPosition = FormStartPosition.CenterScreen;

但是这段代码似乎每次都不起作用......它每次只在主屏幕上显示表单。

4

1 回答 1

4

尝试这个:

foreach(var screen in Screen.AllScreens)
{
   if (screen.WorkingArea.Contains(this.Location))
   {
      var middle = (screen.WorkingArea.Bottom + screen.WorkingArea.Top) / 2;
      Location = new System.Drawing.Point(Location.X, middle - Height / 2);
      break;
   }
}

请注意,如果左上角不在任何屏幕上,这将不起作用,因此最好找到与表单中心距离最小的屏幕。

编辑

如果要在给定屏幕上显示,则必须设置this.StartPosition = FormStartPosition.Manual;

尝试使用此代码:

System.Windows.Forms.Screen[] allScreens = System.Windows.Forms.Screen.AllScreens;
System.Windows.Forms.Screen myScreen = allScreens[0];

int screenId = RegistryManager.ScreenId;
if (screenId > 0)
{
    myScreen = allScreens[screenId - 1];
}

Point centerOfScreen = new Point((myScreen.WorkingArea.Left + myScreen.WorkingArea.Right) / 2,
                                 (myScreen.WorkingArea.Top + myScreen.WorkingArea.Bottom) / 2);
this.Location = new Point(centerOfScreen.X - this.Width / 2, centerOfScreen.Y - this.Height / 2);

this.StartPosition = FormStartPosition.Manual;
于 2010-06-09T10:40:37.937 回答