winform设置窗体居中的方法是什么

   2025-02-19 4140
核心提示:要将Winform窗体居中,可以使用以下方法:使用Screen.PrimaryScreen对象的属性来获取主显示屏的宽度和高度。int screenWidth = Sc

要将Winform窗体居中,可以使用以下方法:

使用Screen.PrimaryScreen对象的属性来获取主显示屏的宽度和高度。
int screenWidth = Screen.PrimaryScreen.Bounds.Width;int screenHeight = Screen.PrimaryScreen.Bounds.Height;
使用Form对象的WidthHeight属性来获取窗体的宽度和高度。
int formWidth = this.Width;int formHeight = this.Height;
计算窗体的左上角坐标,并使用Location属性来设置窗体的位置。
int left = (screenWidth - formWidth) / 2;int top = (screenHeight - formHeight) / 2;this.Location = new Point(left, top);

完整的代码示例:

using System;using System.Drawing;using System.Windows.Forms;namespace CenterForm{public partial class MainForm : Form{public MainForm(){InitializeComponent();}private void MainForm_Load(object sender, EventArgs e){CenterForm();}private void CenterForm(){int screenWidth = Screen.PrimaryScreen.Bounds.Width;int screenHeight = Screen.PrimaryScreen.Bounds.Height;int formWidth = this.Width;int formHeight = this.Height;int left = (screenWidth - formWidth) / 2;int top = (screenHeight - formHeight) / 2;this.Location = new Point(left, top);}}}

在窗体的Load事件中调用CenterForm方法,即可将窗体居中显示。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言