Winform:在显示之前获取表单位置(StartupPosition为CenterScreen)

本文关键字:位置 StartupPosition CenterScreen 表单 获取 显示 Winform | 更新日期: 2023-09-27 17:59:16

有这样的方法吗?根据我的理解,这应该是可能的,但如果我在显示表单之前尝试myForm.Location,我会得到(0, 0)

谢谢!

Winform:在显示之前获取表单位置(StartupPosition为CenterScreen)

了解表单位置的最佳方法是决定要放在哪里。

   Form formDemo = new DemoForm();
   formDemo.Location = new Point(20, 30);
   formDemo.Show(); //or formDemo.ShowDialog();

在@Diego澄清了他的问题后,我相信这将满足需要:

    int ScreenWidth = Screen.PrimaryScreen.WorkingArea.Width;
    int ScreenHeight = Screen.PrimaryScreen.WorkingArea.Height;
    int formTop = (ScreenHeight/2) - (formDemo.Height / 2);
    int formLeft = (ScreenWidth/2) - (formDemo.Width / 2);

我认为从技术上讲,在绘制之前你没有位置。我个人不知道如何将"System.Windows.Forms.FormStartPosition"枚举转换为Point。

不管你想要什么,它应该很简单。我会显示第一个形式,然后将它的边界传递给第二个形式,在那里你可以设置它的启动逻辑,以使用这些逻辑进行定位。

 public Form1()
    {
        InitializeComponent();
        StartPosition = FormStartPosition.CenterScreen;
        this.Shown += new EventHandler(Form1_Shown);
    }
    void Form1_Shown(object sender, EventArgs e)
    {
        ShowForm2(this.Bounds);
    }  
    public void ShowForm2(Rectangle ParentBounds)
    {
        Form2 f = new Form2();
        int x = ParentBounds.Right+2;
        int y = ParentBounds.Y + (ParentBounds.Height/2) - (f.Height/2);
        Point childStartPosition = new Point(x,y);
        f.StartPosition = FormStartPosition.Manual;
        f.Location = childStartPosition;
        f.Show();
    }