如何以编程方式移动表单?

时间:2016-11-30 23:43:33

标签: c# winforms

我是这个C#的新手,需要你的帮助

目前我的表格上有4个按钮(上,下,左,右)

我想将表单移动10个像素到按下的方向。

2 个答案:

答案 0 :(得分:3)

要单独设置它们,请使用表单的左(X)或顶(Y)子属性。 不要尝试隐式设置表示表单位置的Point结构的X和Y坐标,因为它包含表单坐标的副本。

要以增量编程更改表格位置,请增加或减少X和Y坐标

  • 左= X
  • 顶部= Y

示例按钮事件:

private void UpButton_Click(object sender, EventArgs e)    
{
    this.Top -= 10;
}

private void DownButton_Click(object sender, EventArgs e)
{
    this.Top += 10;
}

private void RightButton_Click(object sender, EventArgs e)
{
    this.Left += 10;
}

private void LeftButton_Click(object sender, EventArgs e)
{
    this.Left -= 10;
}
  

澄清例如this.Top -= 10;this.Top = this.Top - 10;

的缩写

结果:

result

答案 1 :(得分:2)

将表单移到右侧:

private void btnRight_Click(object sender, EventArgs e) {
     form.Location = new Point(form.Location.X + 10, form.Location.Y);
}

将表单移到左侧:

private void btnLeft_Click(object sender, EventArgs e) {
     form.Location = new Point(form.Location.X - 10, form.Location.Y);
}  

向上移动表格:

private void btnUp_Click(object sender, EventArgs e) {
     form.Location = new Point(form.Location.X, form.Location.Y - 10);
}  

向下移动表单:

private void btnDown_Click(object sender, EventArgs e) {
     form.Location = new Point(form.Location.X, form.Location.Y + 10);
}  

编辑:
如果表单是指主窗口,只需将代码中的每个“表单”替换为“this”。