要将Winform窗体居中,可以使用以下方法:
1. 使用`Screen.PrimaryScreen`对象的属性来获取主显示屏的宽度和高度。
```csharp
int screenWidth = Screen.PrimaryScreen.Bounds.Width;
int screenHeight = Screen.PrimaryScreen.Bounds.Height;
```
2. 使用`Form`对象的`Width`和`Height`属性来获取窗体的宽度和高度。
```csharp
int formWidth = this.Width;
int formHeight = this.Height;
```
3. 计算窗体的左上角坐标,并使用`Location`属性来设置窗体的位置。
```csharp
int left = (screenWidth - formWidth) / 2;
int top = (screenHeight - formHeight) / 2;
this.Location = new Point(left, top);
```
完整的代码示例:
```csharp
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`方法,即可将窗体居中显示。