我有双显示器,想要在屏幕中央显示一个窗口窗体。 (我有一个变量 MonitorId=0 或 1)。
I have:
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;
但这段代码似乎并不每次都有效...它每次都只在主屏幕上显示表单。
尝试这个:
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;
}
}
请注意,如果左上角不在任何屏幕上,则此方法将不起作用,因此最好找到距表单中心距离最近的屏幕。
Edit
如果你想显示在given屏幕,您必须设置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;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)