在Screen(双屏幕)的中心显示WindowsForm [英] Show WindowsForm in the center of the Screen (Dual Screen)

查看:626
本文介绍了在Screen(双屏幕)的中心显示WindowsForm的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have Dual Monitors and want displaying a windows form in the center of the screen. (I have a variable MonitorId=0 or 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;

但是,这code似乎没有每次工作...它显示的形式,每次在主屏幕上出现。

But this code does not seem to work each time... It displays the form every time on the main screen only.

推荐答案

试试这个:

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.

修改

如果你想显示在的屏幕上,你必须设置 this.StartPosition = FormStartPosition.Manual;

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

尝试使用这种code:

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;

这篇关于在Screen(双屏幕)的中心显示WindowsForm的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆