winforms 将窗口自动移动到具有指定屏幕分辨率的监视器上

f2uvfpb9  于 2022-11-17  发布在  其他
关注(0)|答案(2)|浏览(126)

我有一个应用程序,当它加载某个窗口时,它需要自动移动到分辨率为1920x515的屏幕上。我找到了一种方法来使它工作,但我会寻找一种更有效的方法来做到这一点,因为很明显,这是最糟糕的方法。我该如何改进呢?

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());

                    }
                }

            }
        }```
tuwxkamq

tuwxkamq1#

这段代码根本不移动屏幕,它只是用屏幕的尺寸填充一个组合框,然后将其中的一些保存到应用程序的设置中。
要移动表单,您需要找到目标屏幕的左上角坐标,并将表单移动到这些坐标:

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

pxyaymoc2#

谢谢@Panagiotis Kanavos这解决了我的问题

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

相关问题