2015-06-27 52 views
0

我正在處理一個系統,該系統涉及將一組值輸入到一系列文本框中,然後單擊一個按鈕,將每個文本框中的值添加到它們各自的List<>。 點擊按鈕後,我使用Focus()函數將焦點放在文本框組頂部的文本框中(txtHR)。當使用光標單擊按鈕時,這可以正常工作。C# - if else聲明按鈕單擊和函數調用

唯一的問題是這樣的:

由於有很多文本框的要寫入,我做在那裏打了輸入鍵將焦點下移文本框列表中選擇一個功能(使數據錄入更快)。這導致焦點然後在按鈕btnSaveData上,並且擊中輸入鍵再次有效地執行按鈕點擊。 這會將焦點返回到txtHR,但系統也會接受輸入按鍵並將焦點移到下一個文本框中。

有沒有辦法解決這個問題?我猜這將涉及一個if/else聲明基於它是否是按鈕點擊或按鍵,調用txtHR.Focus()

代碼兩者btnSaveData_ClickControl_KeyUp,如下圖所示:

private void btnSaveData_Click(object sender, EventArgs e) //To be clicked while clock is running 
    { //turn inputted data into outputted data 
     //take the data in the input boxes and... 
     updateLists(); //add to respective list 
     saveReadings(); //append each variable to file 

     //return cursor to top box in list ready for next data set 
     txtHR.Focus(); 
    } 

    private void Control_KeyUP(object sender, KeyEventArgs e) //for selected textboxes and buttons only 
    { 
     if ((e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Return)) 
     { 
      this.SelectNextControl((Control)sender, true, true, true, true); 
     } 
    } 
+4

爲什麼讓Enter鍵改變焦點? Tab鍵和Textbox控件的正確順序應該自動處理 - 不需要模擬Tab鍵。 – NoChance

+1

是否也掛鉤到該事件處理程序的按鈕的KeyUp事件? – Chris

回答

1

你可以測試,以確保在按下Enter鍵的控制是一個TextBox做焦點改變之前,或者有其他類型的控件,你也希望這種焦點轉發行爲,而不是測試它是否爲保存按鈕。類似這樣的:

private void Control_KeyUP(object sender, KeyEventArgs e) //for selected textboxes and buttons only 
{ 
    // Bail if not on a TextBox. 
    if ((sender as TextBox) == null) // **or instead** if ((sender as Button) == this.btnSaveData) 
     return; 

    if ((e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Return)) 
    { 
     this.SelectNextControl((Control)sender, true, true, true, true); 
    } 
}