2010-05-19 4 views
2

J'ai deux moniteurs et je veux afficher une forme de fenêtre au centre de l'écran. (J'ai une variable MonitorId = 0 ou 1).Afficher WindowsForm au centre de l'écran (double écran)

J'ai:

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; 

Mais ce code ne semble pas fonctionner à chaque fois ... Il affiche la forme à chaque fois sur l'écran principal uniquement.

Répondre

4

Essayez ceci:

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; 
    } 
} 

Notez que cela ne fonctionnera pas si le coin supérieur gauche ne figure sur aucun des écrans, il peut être préférable de trouver l'écran avec la plus petite distance du centre de la forme à la place.

Modifier

Si vous souhaitez afficher sur un écran donné, vous devez définir this.StartPosition = FormStartPosition.Manual;

Essayez d'utiliser ce 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; 
+0

Je ne besoin d'afficher le formulaire le même écran qui se trouve réellement ('if (screen.WorkingArea.Contains (this.Location))') mais en fonction de 'screeenID' – serhio

+0

Edited answer for reflect this ... –

Questions connexes