Moving window automatically to a monitor with a specified screen resolution

Viewed 32

I have an application that when it loads a certain window it need to automatically move to the screen that has 1920x515 resolution. I found a way to make it work but I'd be looking for a more efficient way of doing this as clearly this is the worst approach. How can I improve this?

private void ComboBox2_Initialized(object sender, EventArgs e)
        {
            foreach (var screen in Screen.AllScreens)
            {
                // For each screen, add the screen properties to a list box.
                //ComboBox2.Items.Add("Location: "  + screen.Bounds.Location .ToString());
                ComboBox2.Items.Add(screen.Bounds.Left.ToString());
                ComboBox2.Items.Add(screen.Bounds.Width.ToString());
                ComboBox2.Items.Add(screen.Bounds.Top.ToString());
                ComboBox2.Items.Add(screen.Bounds.Height.ToString());

                //double top = 0;
                //double left = 0; 


                if (ComboBox2.Items.Contains("1920"))
                {


                    if (ComboBox2.Items.Contains("515"))
                    {

                        Properties.Settings.Default.Top = screen.Bounds.Top;
                        Properties.Settings.Default.Left = screen.Bounds.Left;


                        Properties.Settings.Default.Save();
                        //System.Windows.MessageBox.Show(Properties.Settings.Default.Left.ToString());

                    }
                }


            }
        }```
2 Answers

This code doesn't move the screen at all. It only fills a combo with the dimensions of the screens, then saves some of them in the application's settings.

To move the form you need to find the top left coordinates of the target screen and move the form to them:

var desired=new Size(1920,515);
var targetScreen= Screen.AllScreens.FirstOrDefault(
                          screen=> screen.Bounds.Size==desired);
if (targetScreen != null)
{
    this.Location=targetScreen.WorkingArea.Location;
}

Thank you @Panagiotis Kanavos This fixed my issue

var desired = new System.Drawing.Size(1920, 515);


            var targetScreen = Screen.AllScreens.FirstOrDefault(
                                      screen => screen.Bounds.Size == desired);

            
            if (targetScreen != null)
            {
                this.Left = targetScreen.WorkingArea.Location.X;
                this.Top = targetScreen.WorkingArea.Location.Y;
            }
Related