2012-05-19 62 views
2

l我的C#winform项目有问题。更换按钮位置

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

私人无效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. 

如果有人可以帮助我,这将帮助我很多:)

回答

2

if语句总是判断为真。这意味着,最终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

+0

当我只用这部分|| ((qY> = q2.Y) ||((qY <= q2.Y)它仍然需要一些按钮的最后一个位置/: –

+0

但我没有要求为什么它总是如此tnx :) –

+0

我didnt undertod我能做些什么来解决按钮的问题我怎么能把按钮区域拿出来按下按钮! –