c# - 更换按钮位置

标签 c# winforms

我的 c# winform 项目有问题。

在我的项目中,我有一个功能,如果按钮位于同一区域,则可以将按钮的位置切换到旧位置。

private void myText_MouseUp(对象发送者,MouseEventArgs e) {

Point q = new Point(0, 0);
        Point q2 = new Point(0, 0);
        bool flag = false;
        int r = 0;
        foreach (Control p in this.Controls)
        {
            for (int i = 0; i < counter; i++)
            {
                if (flag)
                {
                    if (p.Location.X == locationx[i] && p.Location.Y == locationy[i])
                    {
                        oldx = e.X;
                        oldy = e.Y;
                        flag = true;
                        r = i;
                    }
                }
            }
        }
        foreach (Control p in this.Controls)
        {
            for (int j = 0; j < counter; j++)
            {
                if ((locationx[j] == p.Location.X) && (locationy[j] == p.Location.Y))
                {
                    Point arrr = new Point(oldx, oldy);
                    buttons[j].Location = arrr;
                    buttons[r].Location = new Point(locationx[j], locationy[j]);
                }
            }
        }
}
   The problem with this code is that if they are in the same area, the buttons do not switch their locations.  Instead they goes to the last button location.

如果有人可以帮助我,那会对我有很大帮助:)

最佳答案

if语句的计算结果始终为 true。这意味着最终的j循环将执行以下操作:

// last time round the i loop, i == counter-1
// and q == new Point(locationx[counter-1], locationy[counter-1])
for (int j = 0; j < counter; j++)
{
    Point q2 = new Point(locationx[j], locationy[j]);
    buttons[i].Location = q2;
    buttons[j].Location = q;
}

最终结果是每个按钮的 Location设置为q ,即

new Point(locationx[counter-1], locationy[counter-1])

为什么if语句的计算结果始终为 true 。好吧,首先让我们看一下 or 中的几个if 中的条款声明:

|| ((q.Y >= q2.Y) && (q.X <= q2.X))
|| ((q.Y >= q2.Y) && (q.X == q2.X))

这相当于

|| ((q.Y >= q2.Y) && (q.X <= q2.X))

包含 == 的行测试对条件的最终结果绝对没有影响。事实上,所有包含 == 的行可以进行类似处理。这留下:

|| ((q.Y >= q2.Y) && (q.X <= q2.X))
|| ((q.Y >= q2.Y) && (q.X >= q2.X))
|| ((q.Y <= q2.Y) && (q.X >= q2.X))
|| ((q.Y <= q2.Y) && (q.X <= q2.X))

我们可以压缩

|| ((q.Y >= q2.Y) && (q.X <= q2.X))
|| ((q.Y >= q2.Y) && (q.X >= q2.X))

进入

|| ((q.Y >= q2.Y)

类似

|| ((q.Y <= q2.Y) && (q.X >= q2.X))
|| ((q.Y <= q2.Y) && (q.X <= q2.X))

相同
|| ((q.Y <= q2.Y)

合并

|| ((q.Y >= q2.Y)
|| ((q.Y <= q2.Y)

您可以看到 if条件的计算结果始终为 true .

关于c# - 更换按钮位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10663481/

相关文章:

c# - 更改类对象列表中项目值的正确方法

c# - 使用 .Net 持久存储加密数据

c# - 以基本形式定义的自定义属性在重建时以继承形式丢失其状态

c# - 为什么 WinForms 标签不想透明的原因?

c# - 如何在 winform 中使用 UI 托管控制台 exe

c# - DDD 限界上下文 "integration"

c# - 调整子项大小时保持滚动查看器的相对滚动条偏移量

c# - 给 Sprite 添加力量

c# - Invalidate()将东西留在屏幕上

c# - 如何防止应用程序运行时数据网格中的行闪烁