Show WindowsForm in the center of the Screen (Dual Screen)

纵饮孤独 提交于 2019-12-06 07:24:05

Try this:

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

Note that this will not work if the top-left corner is not on any of the screens, so it may be better to find the screen with the least distance from the center of the form instead.

Edit

If you want to display on a given screen, you must set this.StartPosition = FormStartPosition.Manual;

Try using this code:

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;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!