我有双显示器,并希望在屏幕中央显示一个窗体。 (我有一个变量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;
但是这段代码似乎每次都不起作用......它每次都只在主屏幕上显示表格。
答案 0 :(得分: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;