Programming for Multiple Screens in DotNET


This is a piece of code I used for an application that needed to be displayed in 2 screens setup as extended view. I used a simple calculation to know the selected screen's coordinates and place the form in its center. To try out the code listed below create 2 forms (Form1 and Form2). In form1 create a combobox and a button, name them screensComboBox and displayButton respectively. In Form2 set its StartupPosition to Manual. Then paste the code below in Form1 replacing the whole class.

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            
            //display a list of available screens
            foreach (Screen S in Screen.AllScreens)
            {
                screensComboBox.Items.Add("Screen " + 
                    S.DeviceName.Substring(S.DeviceName.Length - 1, 1));
            }

            screensComboBox.SelectedIndex = 0;
        }

        private void displayButton_Click(object sender, EventArgs e)
        {
            //get the selected screen's X and Y coordinates, and its size
            Rectangle screenRec = 
                Screen.AllScreens[screensComboBox.SelectedIndex].Bounds;
            Form2 form2 = new Form2();

            //screens starting pixel + half its size - half the size of the form            
            form2.Left = screenRec.X + ((screenRec.Width / 2) - (form2.Width / 2));
            form2.Top = screenRec.Y + ((screenRec.Height / 2) - (form2.Height / 2));            
            form2.Show();            
        }
    }