手动定位与窗体居中#
来源:
D:\study\C#1\WinForm\stu0804\01、stu0811\stu0811
1. 手动定位(Location / Size)#
// 设置位置和大小
button.Location = new Point(100, 200);
button.Size = new Size(80, 30);
// 动态移动
button.Location = new Point(x += 10, y);
// 相对当前位置移动
button.Left += 10; // 向右移 10
button.Top += 10; // 向下移 10
💡
Left/Top是Location.X/Location.Y的快捷属性,Width/Height同理。
2. 窗体居中(两种方式)#
方式一:StartPosition 属性(最简)#
方式二:手动计算(控件在窗体中居中)#
// Load 事件中计算(加载时执行一次)
private void Form1_Load(object sender, EventArgs e)
{
int W = (this.ClientSize.Width - this.panel1.Size.Width) / 2;
int H = (this.ClientSize.Height - this.panel1.Size.Height) / 2;
this.panel1.Location = new Point(W, H);
}
// SizeChanged 事件中计算(窗体大小改变时重新居中)
private void Form1_SizeChanged(object sender, EventArgs e)
{
int W = (this.ClientSize.Width - this.panel1.Size.Width) / 2;
int H = (this.ClientSize.Height - this.panel1.Size.Height) / 2;
this.panel1.Location = new Point(W, H);
}
💡 居中公式:
(容器宽 - 控件宽) / 2、(容器高 - 控件高) / 2。 用ClientSize而不是Size,因为ClientSize不含标题栏和边框,更准确。
3. 三种居中场景对照#
| 场景 | 做法 |
|---|---|
| 窗体在屏幕居中 | StartPosition = FormStartPosition.CenterScreen |
| 控件在窗体居中(固定) | Load 事件中计算一次 |
| 控件随窗体缩放保持居中 | SizeChanged 事件中重新计算 |
4. 布局三兄弟对比#
| 方式 | 特点 | 适用 |
|---|---|---|
| 手动定位 | 精确控制每个控件位置 | 固定大小界面 |
| Anchor 锚定 | 控件相对父容器边距固定 | 窗体缩放时保持相对位置 |
| Dock 停靠 | 控件贴住父容器某边/填满 | 面板式布局 |
后面两篇分别介绍 Anchor/Dock 与 TableLayoutPanel/FlowLayoutPanel,组合使用可以做到界面自适应。
相关笔记#
- 坐标系统与控件定位 — 坐标系统
- Dock 与 Anchor — Dock 与 Anchor