2014-04-04 67 views
0

我在我的窗體中有兩個按鈕和一個標籤和一個計時器控件。 在計時器滴答事件我所做的:爲什麼要將文字移動到左側劑量的左側菜單中?

private void timer2_Tick(object sender, EventArgs e) 
{ 
    if (mode == "Left-to-Right") 
    { 
     if (this.Width == xpos) 
     { 
      this.label1.Location = new System.Drawing.Point(0, ypos); 
      xpos = 0; 
     } 
     else 
     { 
      this.label1.Location = new System.Drawing.Point(xpos, ypos); 
      xpos += 2; 
     } 
    } 
    else if (mode == "Right-to-Left") 
    { 
     if (xpos == 0) 
     { 
      this.label1.Location = new System.Drawing.Point(this.Width, ypos); 
      xpos = this.Width; 
     } 
     else 
     { 
      this.label1.Location = new System.Drawing.Point(xpos, ypos); 
      xpos -= 2; 
     } 
    } 
} 

然後點擊一個按鈕事件:

private void button2_Click_1(object sender, EventArgs e) 
{ 
    xpos = label2.Location.X; 
    ypos = label2.Location.Y; 
    mode = "Left-to-Right"; 
    timer2.Start(); 
} 

和一個按鈕單擊事件:

private void button3_Click_1(object sender, EventArgs e) 
{ 
    xpos = label2.Location.X; 
    ypos = label2.Location.Y; 
    mode = "Right-to-Left"; 
    timer2.Start(); 
} 

當我BUTTON2點擊使它當文字到達右側時,文字就像從邊界/邊界向內移動,然後從左側返回,從左向右移動它的效果很好。

但是,當我點擊按鈕從右到左,一旦文本到達左邊界/邊界的文本消失/ disapear第二,然後開始從原來的位置mvoe。爲什麼它沒有按照從左到右的按鈕2進行操作?

編輯**

這是我改變:

private void timer2_Tick(object sender, EventArgs e) 
{ 
    if (mode == "Left-to-Right") 
    { 
     if (this.Width == xpos) 
     { 
      this.label1.Location = new System.Drawing.Point(0, ypos); 
      xpos = 0; 
     } 
     else 
     { 
      this.label1.Location = new System.Drawing.Point(xpos, ypos); 
      xpos += 2; 
     } 
    } 
    else if (mode == "Right-to-Left") 
    { 
     if (xpos < -label2.Width) 
     { 
      this.label1.Location = new System.Drawing.Point(this.Width, ypos); 
      xpos = this.ClientSize.Width - label2.Width; 
     } 
     else 
     { 
      this.label1.Location = new System.Drawing.Point(xpos, ypos); 
      xpos -= 2; 
     } 
    } 
} 
+0

有幾個錯誤。 this.Width包含邊框,請改用this.ClientWidth。爲了使它對稱,你需要'if(xpos <-label2.Width)'而不是'if(xpos == 0)'來允許它滾動窗口。然後在'xpos = this.ClientWidth - label2.Width'重新啓動它。 –

+0

Hans看着我編輯的問題,現在我做的工作還不夠好。 – user3482138

+0

現在你只是添加錯誤。交換兩個語句並使用this.label1.Location = new System.Drawing.Point(xpos,ypos); –

回答

0

如果this.Width爲奇數這是行不通的。嘗試改變這種

if (this.Width == xpos) 

這樣:

if (this.Width >= xpos) 

它通常是一個好主意,不測試換號是否相等。測試greater thanless thangreater or equal ..這稱爲防禦性編程,不花你任何東西,使你的代碼更健壯。