在 C# 中使用箭头键聚焦文本框

时间:2020-12-29 20:04:01

标签: c# forms keyboard-shortcuts

我在这个表单上有很多文本框;怎么用方向键一个一个对焦?

或者我怎样才能让下面的代码更简单易读?

此代码是基本的,用于有限的文本框,但我无法将相同的行重写到每个文本框中。

40 为向下键,38 为向上键

my form picture, please see it

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(); }
}

2 个答案:

答案 0 :(得分:0)

我的一个想法是:

您有一个变量 (int counter = 0;) 和一个文本框列表 (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();
}

这个想法是整数 counter 表示当前具有焦点的列表 textBoxes 中 TextBox 的索引。单击按钮时,它会通过变量 counter 更改获得焦点的 TextBox 并获得焦点。

注意,这个事件方法必须分配给所有的文本框!

希望它是您正在寻找的,并且对您有所帮助!

答案 1 :(得分:0)

另一种方法是直接从 FORM 中捕获按下的键。 为此,您必须启用 KeyPreview 属性。更多信息请点击enter link description here

您可以使用

    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(); 

    }
相关问题