用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;(和一个文本框列表(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并获取焦点。

请注意,此事件方法必须分配给所有的TextBoxes!

希望这是你想要的,对你有帮助!

另一种方法是直接从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(); 
}

最新更新