簡體   English   中英

通過 C# 中的箭頭鍵通過 TextBoxes 聚焦

[英]Focus through TextBoxes with arrows keys in C#

我在這個表格上有很多文本框; 如何使用箭頭鍵一一對焦?

或者我怎樣才能使下面的代碼更容易和可讀?

這段代碼是基本的,用於我認為有限的文本框,但我不能將相同的行重寫到每個文本框中。

40是向下鍵,38是向上鍵

我的表格圖片,請看

private void t1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
    if (e.KeyValue == 40) { t1a.Focus(); }
    if (e.KeyValue == 38) { t1c.Focus(); }
}

private void t1a_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
    if (e.KeyValue == 40) { t1b.Focus(); }
    if (e.KeyValue == 38) { t1.Focus(); }
}

private void t1b_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
    if (e.KeyValue == 40) { t1c.Focus(); }
    if (e.KeyValue == 38) { t1a.Focus(); }
}

private void t1c_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
    if (e.KeyValue == 40) { t1.Focus(); }
    if (e.KeyValue == 38) { t1b.Focus(); }
}

我的一個想法是:

您有一個變量( int counter = 0; )和一個 TextBoxes 列表( List<TextBox> textBoxes = new(); )。 在列表中,有您使用的所有文本框,按照您希望它們被點擊的順序排列。

例如:

private void PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
    if (e.KeyValue == 40) { counter--; }
    else if (e.KeyValue == 38) { counter++; }
    textBoxes[counter].Focus();
}

這個想法是 integer counter表示當前具有焦點的列表textBoxes中的 TextBox 的索引。 單擊按鈕時,它通過變量counter更改焦點文本框並獲得焦點。

請注意,此事件方法必須分配給所有文本框!

希望它是你正在尋找的,它可以幫助你!

另一種方法是直接從 FORM 中捕獲按下的鍵。 為此,您必須啟用KeyPreview屬性。 更多信息在這里輸入鏈接描述

您可以使用

    void MainFormLoad(object sender, EventArgs e) 
      { 
       this.KeyPreview=true;        
      }

然后

    void MainFormKeyDown(object sender, KeyEventArgs e)
    {   
        
        // Make a list of textBoxes
        List<string> mylist = new List<string>(new string[] { "t1", "t1a" , "t1b",  "t1c"});
        
        //Get the name of CurrentTextBox
        string CurrentTextBox=ActiveControl.Name;
        
        //Get the index of the CurrentTextBox in textBoxes list
        int index= mylist.IndexOf(CurrentTextBox);
        
        //Check the KeyCode and walk throught the list: {"t1", "t1a" , "t1b",  "t1c"}.
        //if the value of "index" is be negative or over range we will rearrange it.
        
        if (e.KeyCode.ToString()=="Up")   index--;  if (index < 0)  index=mylist.Count-1;
        if (e.KeyCode.ToString()=="Down") index++;  if (index >= mylist.Count) index=0;
        
        //Set the desired textbox to be focused.
        Controls[mylist[index]].Focus(); 

    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM