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

廉价感情. 提交于 2019-12-20 02:24:12

问题


I have a form that is centered according to the screen position that I resize by fontsize when loading. After resizing the location remains the same as it was before resizing so the form is no longer in the center, like I would like.

Let me draw you a sketch:

I've tried calling

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

again after resizing (this is, I believe, the part of the code that centers the form in the beginning). It didn't work. I've also found some similar issues like this: "Keeping winform control centered after window resize " but they always only deal with centring a control, not the form itself.


回答1:


Add method for ResizeEnd event. In method, when ResizeEnd is fired, get current screen size (on multiple monitors, screen that contains current form) and then calculate form's position. Take a look at this example

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


来源:https://stackoverflow.com/questions/45877908/how-to-keep-form-centered-to-the-middle-of-the-screen-after-resize

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!