2017-07-31 96 views
0

在button3_click我需要我的計數器開始從0C#如何點擊一個按鈕啓動計數器,然後重新啓動並在另一個按鈕上單擊增加相同的計數器?

 static int btncntr=0; 
     private void button2_Click(object sender, EventArgs e) 
    { 
     btncntr++; 
     timer1.Stop(); 
     timer1.Start(); 
     string a = GetLetter(2); 
     char b = char.Parse(a); 
     SetLetter(b); 
    } 
     private void button3_Click(object sender, EventArgs e) 
    { 
      btncntr++; 
      timer1.Stop(); 
      timer1.Start(); 
      string a = GetLetter(3); 
      char b = char.Parse(a); 
      SetLetter(b); 
    } 

我試圖模擬短信打字計數。在button2上有ABC,在按鈕3上有DEF。如果我點擊一次button2我應該得到A,雙擊給我B等 如果我點擊一次button2和一次button3我得到的是AE而不是AD。每個按鈕都有計數器會很複雜,我更喜歡這種方式。謝謝。 :)

+2

聽起來像是一個非常簡單的設計問題 - 不是一個代碼問題..你已經確定了你爲什麼會遇到問題。問問你自己,你是如何做到的。在你的腦海裏,你可能會記得幾個按鈕,但是如果我給你1000個按鈕,你會怎麼建議呢? – BugFinder

回答

0

這應該這樣做....

static int btncntr=0; 
static int lastButton=0; 

private void button2_Click(object sender, EventArgs e) 
{ 
    //if the last click wasnt button 2 then reset 
    if(lastButton != 2) 
     btncntr = 0; 

    //save last button clicked 
    lastButton = 2; 

    btncntr++; 
    timer1.Stop(); 
    timer1.Start(); 
    string a = GetLetter(2); 
    char b = char.Parse(a); 
    SetLetter(b); 
} 

private void button3_Click(object sender, EventArgs e) 
{ 
    //if the last click wasnt button 3 then reset 
    if(lastButton != 3) 
     btncntr = 0; 

    //save last button clicked 
    lastButton = 3; 

    btncntr++; 
    timer1.Stop(); 
    timer1.Start(); 
    string a = GetLetter(3); 
    char b = char.Parse(a); 
    SetLetter(b); 
} 
+0

非常感謝。它解決了我的問題。下次我應該找出類似的東西。 – AndjelaS

1

SetLetter後,您需要重置計數器,

SetLetter(b); 
btncntr=0; 
+0

如果你這樣做,它將永遠是1.很難說,因爲我們沒有GetLetter和SetLetter的代碼,但我懷疑它需要重置,如果GetLetter被調用與上次調用不同的輸入。 – ajg

+0

比需要啓動int的方法。 – raichiks

相關問題