繁体   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