-1

我的 winform c# 项目有问题。在我的项目中,我有两个主要功能,一个在运行时制作按钮,另一个功能允许我在运行时移动表单上的按钮。现在,如果我在其他按钮上有按钮,我该怎么办,所以我制作了替换按钮位置的功能,但如果有人可以帮助我,该功能会出现问题,那就太好了!

public void upandunder(Button cBtn1, Button cBtn2)
    {
        if ((cBtn1.Location.X == cBtn2.Location.X) && (cBtn1.Location.Y == cBtn2.Location.Y))
        {
            int placex = cBtn1.Location.X;
            int placey = cBtn1.Location.Y;
            cBtn1.Location.X = cBtn2.Location.Y;
            cBtn1.Location.Y = cBtn2.Location.Y;
            cBtn2.Location.X = placex;
            cBtn2.Location.Y = placey;

        }
    }
4

3 回答 3

1

它让我认为errorError 1无法修改'System.Windows.Forms.Control.Location'的返回值,因为它不是变量

正确,Location属性的返回值不可编辑。根据文档

因为Point类是值类型(Structure在 Visual Basic 中,struct在 Visual C# 中),所以它是按值返回的,这意味着访问该属性会返回控件左上角的副本。因此,调整从该属性返回的XorY属性Point不会影响控件的Left, Right, Top, orBottom属性值。要调整这些属性,请单独设置每个属性值,或Location使用新的Point.

因此,您需要将代码重写为以下内容:(
另外,我强烈建议将参数命名为 and 以外的名称xy因为您正在处理函数中具有 x 和 y 值的坐标...)

public void upandunder(Button btn1, Button btn2)
{
    if ((btn1.Location.X == btn2.Location.X) && (btn1.Location.Y == btn2.Location.Y))
    {
        Point originalLocation = btn1.Location;
        btn1.Location = btn2.Location;
        btn2.Location = originalLocation;
    }
}

甚至更好,只需比较属性Point返回的两个值LocationPoint结构重载==operator):

public void upandunder(Button btn1, Button btn2)
{
    if (btn1.Location == btn2.Location)
    {
        Point originalLocation = btn1.Location;
        btn1.Location = btn2.Location;
        btn2.Location = originalLocation;
    }
}

当然,我看不出它是如何完成任何事情的。首先,您检查按钮是否位于彼此之上(具有完全相同的 x 和 y 坐标),然后如果有,则交换它们的位置。它们已经处于相同的位置——您在执行交换代码之前对其进行了测试。

从您的函数名称来看(upandunder应该UpAndUnder遵循标准的 .NET 命名约定),您似乎希望更改按钮的 Z 顺序。如果是这种情况,那么您应该调用按钮控件的BringToFrontSendToBack方法。

于 2012-05-13T13:00:24.117 回答
0

控件上的Location属性返回一个点。Point 结构具有您正在使用的 X 和 Y 值。我认为您不想直接访问它们,而是想提供新的位置点。

试试这个(它适用于我的机器)

public void UpAndUnder(Button cBtn1, Button cBtn2)
{
    if (cBtn1.Location == cBtn2.Location.Y)
    {                
        Point oldPoint = new Point(cBtn1.Location.X, cBtn1.Location.Y);
        cBtn1.Location = new Point(cBtn2.Location.X, cBtn2.Location.Y);
        cBtn2.Location = oldPoint;
    }
}
于 2012-05-13T13:02:01.937 回答
0

如果您想将一个按钮放在另一个按钮上,只需调用

button1.BringToFront();

这将改变 button1 的 Z 顺序并将其置于所有其他控件之上。

于 2012-05-13T13:03:39.777 回答