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 に答える