跳转至

坐标系统与控件定位#

来源D:\study\C#1\WinForm\stu0804\练习stu0811\stu0811


1. WinForms 坐标系统#

(0,0) ──────────────────────► X 增大(向右)
 │         panel1
 │    ┌──────────────┐
 │    │  button3     │
 │    │  (x, y)      │
 │    └──────────────┘
Y 增大(向下)
  • 原点 (0,0) 在窗体/容器的左上角
  • X 向右增大,Y 向下增大(与数学坐标系相反)
  • 坐标单位是像素

2. 控件定位三要素#

// 1. Location(位置)— Point 结构
button.Location = new Point(100, 200);  // 左上角坐标

// 2. Size(大小)— Size 结构
button.Size = new Size(80, 30);         // 宽 × 高

// 3. 获取当前值
int x = button.Location.X;             // 当前 X 坐标
int y = button.Location.Y;             // 当前 Y 坐标
int w = button.Size.Width;             // 宽度
int h = button.Size.Height;            // 高度

💡 记住Location 是控件左上角的位置。移动控件就是改 Location

3. 用变量追踪位置#

在练习项目中用 xy 两个变量记录控件的当前位置:

int x = 0;   // 记录 button3 当前的 X 坐标
int y = 0;   // 记录 button3 当前的 Y 坐标

// 移动:x/y 自增后赋给 Location
button3.Location = new Point(x += 5, y);   // 向右移 5 像素
button3.Location = new Point(x, y -= 5);   // 向上移 5 像素

💡 实际上可以直接读取 button3.Location.X/Y,用变量记录是为了理解和调试方便。

4. 边界判断(限制移动范围)#

4.1 四种方向的边界#

// 上:不能超出顶部(Y 最小为 0)
if (button3.Location.Y > 0)
    button3.Location = new Point(x, y -= 5);

// 下:不能超出底部(Y + 自身高度 <= 容器高度)
if (button3.Location.Y < panel1.Height - button3.Height)
    button3.Location = new Point(x, y += 5);

// 左:不能超出左边(X 最小为 0)
if (button3.Location.X > 0)
    button3.Location = new Point(x -= 5, y);

// 右:不能超出右边(X + 自身宽度 <= 容器宽度)
if (button3.Location.X < panel1.Width - button3.Width)
    button3.Location = new Point(x += 5, y);

4.2 公式总结#

上边界:button.Location.Y > 0
下边界:button.Location.Y < panel1.Height - button.Height
左边界:button.Location.X > 0
右边界:button.Location.X < panel1.Width - button.Width

💡 关键理解panel1.Height - button.Height 是「容器高度减去控件自身高度」,得到的是控件左上角能到达的最大 Y 值

4.3 常见错误#

// 错误:下方向用了 Width 而不是 Height
if (button3.Location.Y < panel1.Height - button3.Width)   // 错!

// 正确
if (button3.Location.Y < panel1.Height - button3.Height)  // 对

5. 窗体居中(手动计算)#

// 方式一: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。这是 WinForms 中最常用的居中写法。


相关笔记#