Form.StartPosition在屬性窗口或代碼中設置 StartPosition 枚舉值,即可控制窗體首次顯示位置:
| 枚舉值 | 行為描述 | 適用場景 |
|---|---|---|
Manual | 由 Location 屬性決定(坐標相對屏幕) | 固定坐標、記憶上次位置 |
CenterScreen | 居中於當前顯示器 | 對話框、主窗體(默認推薦) |
WindowsDefaultLocation | Windows 默認位置(左上角瀑布流排列) | 多文檔界面 (MDI) 子窗體 |
WindowsDefaultBounds | Windows 默認位置和大小 | 很少使用 |
CenterParent | 居中於父窗體(需設置 Owner) | 模態對話框 |
選中窗體 → 屬性窗口 → StartPosition → 選擇 CenterScreen
public Form1()
{
InitializeComponent();
// 方式 A:居中顯示
this.StartPosition = FormStartPosition.CenterScreen;
// 方式 B:指定絕對坐標 (需 StartPosition = Manual)
this.StartPosition = FormStartPosition.Manual;
this.Location = new Point(100, 100); // 屏幕坐標
// 方式 C:右下角對齊 (需手動計算)
this.StartPosition = FormStartPosition.Manual;
Rectangle screen = Screen.PrimaryScreen.WorkingArea;
this.Location = new Point(
screen.Width - this.Width,
screen.Height - this.Height
);
}
// 保存位置 (FormClosing 事件)
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Properties.Settings.Default.WindowLocation = this.Location;
Properties.Settings.Default.WindowSize = this.Size;
Properties.Settings.Default.Save();
}
// 恢復位置 (構造函數中)
public Form1()
{
InitializeComponent();
if (!Properties.Settings.Default.WindowLocation.IsEmpty)
{
this.StartPosition = FormStartPosition.Manual;
this.Location = Properties.Settings.Default.WindowLocation;
this.Size = Properties.Settings.Default.WindowSize;
}
else
{
this.StartPosition = FormStartPosition.CenterScreen; // 首次運行居中
}
}
// 確保窗體在可視區域內
private void EnsureVisibleOnScreen()
{
Rectangle bounds = this.Bounds;
bool moved = false;
foreach (Screen screen in Screen.AllScreens)
{
if (screen.WorkingArea.IntersectsWith(bounds))
{
return; // 已在可視屏幕上
}
}
// 不在任何屏幕可視區,強制移回主屏幕居中
this.StartPosition = FormStartPosition.CenterScreen;
}
| 現象 | 原因 | 解決 |
|---|---|---|
設置 Location 無效 | StartPosition 不是 Manual | 先設置 StartPosition = FormStartPosition.Manual |
| 窗體顯示在屏幕外 | 坐標超出屏幕分辨率,或多屏拔插導致 | 調用 EnsureVisibleOnScreen() 或重置設置 |
| MDI 子窗體位置異常 | MDI 子窗體忽略 StartPosition | 在 MdiChildActivate 或 Layout 事件中手動定位 |
CenterScreen 獲得最佳用戶體驗。StartPosition = Manual + 設置 Location。Properties.Settings,並處理多屏/分辨率變化異常情況。