winform运行中怎么用C# 代码调整窗口位置,特别是怎么居中到屏幕中央??? 设置属性 StartPosion 不行

2024-12-19 00:14:33
推荐回答(3个)
回答1:

获取当前屏幕分辨率->获取当前窗口大小->计算如果居中的话当前窗口的位置->给当前窗口位置赋值
方法挺笨的,不过可以实现,代码如下,测试通过。
int height = System.Windows.Forms.SystemInformation.WorkingArea.Height;
int width = System.Windows.Forms.SystemInformation.WorkingArea.Width;

int formheight = this.Size.Height;
int formwidth = this.Size.Width;

int newformx = width / 2 - formwidth / 2;
int newformy = height / 2 - formheight / 2;

this.SetDesktopLocation(newformx, newformy);

回答2:

屏幕居中:this.StartPosition = FormStartPosition.CenterScreen;
调整位置: this.Location = new Point(X, Y);

回答3:

private void button4_Click(object sender,EventArgs e)
{
this.Location = new Point(
(System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Width-this.Width)/2,
(System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Height-this.Height)/2
);
}