Starting apps on secondary screen.


We have all tried: "Sitting in front of a computer with multiple screens, and wondered how I get my App to start on the other screen?"
Well maybe it's not all of you, but I have :-)


In c# there’s actually a simple solution:
System.Windows.Forms.Screen.AllScreens

This collection contains a list of all screens that is attached to the computer your app is running on.
Using this list you can move the main window to any other screen :-)

The following examples assume that you put the code in the Main window's code!

First off let's sort the list in a smart way. E.g.
var screens = System.Windows.Forms.Screen.AllScreens.
OrderBy(s=>s.X).OrderBy(s=>s.Y).OrderBy(s=>s.Primary?1:0).ToArray();


Now the primary screen is index 0, and all other screens is ordered by the Topmost screen first, and left most first if they are next to each other’s. Note that the sorting can be done more efficient, but sorting is not the primary topic here.

Now that we have a list of screens we need to reposition the app to the correct screen. But this can only be done if it's not maximized.

// Save the current state
WindowState currentWindowState = this.WindowState == WindowState.Maximized; 
// Set the window state to a state where we can reposition.
this.WindowState == WindowState.Normal;


So first we remember the current window state and then set it to normal (So that we can restore the window state afterwards).
Now we can reposition to E.g. the secondary screen.

var screen = screens[0]; // If only one screen is awaiable use it :-)
if(screens.lenght >= 2) 
 screen = screens[1]; // If secondary screen exixts use that instead.

// Now set the curret window to the new location
this.Left = screen.WorkingArea.X; 
this.Top = screen.WorkingArea.Y;

// Last but not least restore window state.
this.WindowState = currentWindowState;


If you want the app to start on another screen (And not move there after it was shown on the first screen) put code in the main window's Loaded Event handler.