views:

220

answers:

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).

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;

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

A: 

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;
gt
I dont need to display the form on the same screen that is actually located (`if (screen.WorkingArea.Contains(this.Location))`) but in dependence of the `screeenID`
serhio
Edited answer to reflect this...
gt