两个按钮的互换位置

时间:2013-06-03 16:40:59

标签: c# button position

我想点击它时用黑色按钮替换按钮位置(交换位置),它紧挨着黑色按钮(b9 =黑色按钮,lable1是保存位置的温度)。

我制作了这个方法:

void checkLocation()
    {
        if (ActiveControl.Location == new Point(5, 7))//-----------for button 1
        {
            if (b9.Location == new Point(83, 7) || b9.Location == new Point(5, 71))
            {
                label1.Location = ActiveControl.Location;
                ActiveControl.Location = b9.Location;
                b9.Location = label1.Location;
            }
        }// it continue for every button

我为每个button_click

编写了这段代码
private void button1_Click(object sender, EventArgs e)
    {
       checkLocation();
    }

现在,某些按钮目前无效。怎么了?

2 个答案:

答案 0 :(得分:1)

感谢p.s.w.g 我认为它更短更合适:

void swapLocation()
    {
        var tmp = ActiveControl.Location;

        if((ActiveControl.Location.X==b9.Location.X)&&(Math.Abs(b9.Location.Y-ActiveControl.Location.Y)<=60))
            {
             ActiveControl.Location = b9.Location;
             b9.Location = tmp;
            }
        if ((ActiveControl.Location.Y == b9.Location.Y) && (Math.Abs(b9.Location.X-ActiveControl.Location.X) <= 70))
            {
            ActiveControl.Location = b9.Location;
            b9.Location = tmp;
            }
        }

答案 1 :(得分:0)

这样做可以交换两个控件的位置:

void swapLocation()
{
    var tmp = ActiveControl.Location;
    ActiveControl.Location = b9.Location;
    b9.Location = tmp;
}

或者更一般地说

void swapLocation(Control x, Control y)
{
    var tmp = x.Location;
    x.Location = y.Location;
    y.Location = tmp;
}

...
swapLocation(ActiveControl, b9);

<强>更新

您似乎正在尝试实施15-puzzle的版本。有很多方法可以解决这个问题,但为了避免彻底改写你的程序,我建议你这样做:

private int buttonWidth = 82;
private int buttonHeight = 82; // adjust these values as needed

private void button_Click(object sender, EventArgs e)
{
   if ((Math.Abs(ActiveControl.Location.X - b9.Location.X) == 0 &&
        Math.Abs(ActiveControl.Location.Y - b9.Location.Y) == buttonHeight) ||
       (Math.Abs(ActiveControl.Location.X - b9.Location.X) == buttonWidth &&
        Math.Abs(ActiveControl.Location.Y - b9.Location.Y) == 0))
   {
       swapLocation(ActiveControl, b9);
   }
}

这基本上会检查ActiveControl是在b9的正上方,下方,左侧还是右侧,如果是,则交换它们。您可以对所有按钮1到8使用此单击处理程序。请注意,此方法 适用于按钮的固定宽度和高度。