2012-05-19 98 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我能做些什麼來解決按鈕的問題我怎麼能把按鈕區域拿出來按下按鈕! –