要將Winform窗體居中,可以使用以下方法:
Screen.PrimaryScreen
對象的屬性來獲取主顯示屏的寬度和高度。int screenWidth = Screen.PrimaryScreen.Bounds.Width;
int screenHeight = Screen.PrimaryScreen.Bounds.Height;
Form
對象的Width
和Height
屬性來獲取窗體的寬度和高度。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
方法,即可將窗體居中顯示。