Winformでフォームを中央揃えにする方法は?

Winform窗体を中央に配置するには、次の方法を使用します。

  1. スクリーン。プライマリスクリーン
int screenWidth = Screen.PrimaryScreen.Bounds.Width;
int screenHeight = Screen.PrimaryScreen.Bounds.Height;
  1. 生まれつきに本質的に
  2. 身長
int formWidth = this.Width;
int formHeight = this.Height;
  1. 所在地
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メソッドを呼び出すことで、フォームを画面中央に配置できます。

bannerAds