调整大小后如何使表单居中于屏幕中间

How to keep form centered to the middle of the screen after resize

我有一个根据屏幕位置居中的表单,我在加载时通​​过 fontsize 调整大小。调整大小后,位置与调整大小前保持不变,因此表格不再位于中心,就像我希望的那样。

我给你画个草图:

我试过打电话

        this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
        this.ResumeLayout(false);
        this.PerformLayout();

在调整大小后再次进行(我相信这是代码的一部分,在开始时将表单居中)。它没有用。我还发现了一些类似的问题: “在 window 调整大小后保持 winform 控件居中 " 但他们总是只处理居中控件,而不是表单本身。

ResizeEnd 事件添加方法。在方法中,当触发 ResizeEnd 时,获取当前屏幕大小(在多个监视器上,包含当前表单的屏幕),然后计算表单的位置。看看这个例子

private void Form1_ResizeEnd(object sender, EventArgs e)
{
    Screen myScreen = Screen.FromControl(this);
    Rectangle area = myScreen.WorkingArea;

    this.Top = (area.Height - this.Height) / 2;
    this.Left = (area.Width - this.Width) / 2;
}