简体   繁体   English

通过按Enter键聚焦选定的控件

[英]Focus selected controls by pressing Enter Key

In C# windows application to navigate all control of a Form (using Enter Key) I am using the below code: 在C#Windows应用程序中,导航一个窗体的所有控件(使用Enter键),我使用以下代码:

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyData == System.Windows.Forms.Keys.Enter)
    {
        SendKeys.Send("{TAB}");
    }
}

NB: Form Property KeyPreview = True; 注意:表单属性KeyPreview = True;

The above code works fine but when I am going to navigate between two dateTimePicker ( dateTimePicker1 , dateTimePicker2 ) pressing Enter Key. 上面的代码工作正常,但是当我要在两个dateTimePickerdateTimePicker1dateTimePicker2 )之间导航时,按Enter键。 When Form open Focus on dateTimePicker1 and press Enter Key then Focus dateTimePicker2 and press Enter Key Focus dateTimePicker1 . 当窗体打开Focus on dateTimePicker1并按Enter键,然后Focus dateTimePicker2并按Enter键Focus dateTimePicker1

The below code works fine without the above code. 没有上面的代码,下面的代码可以正常工作。 What is the best way to navigate the two dateTimePicker using the above code or any other way? 使用上面的代码或其他任何方式浏览两个dateTimePicker的最佳方法是什么?

private void dateTimePicker1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter) {
        dateTimePicker2.Focus();
    }
}

private void dateTimePicker2_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter) {
        dateTimePicker1.Focus();
    }
}

Anybody please help me. 有人请帮助我。

You can subscribe your two DateTimePickers to the same event handler instead of using two events, and use the sender object: 您可以将两个DateTimePickers预订到同一事件处理程序,而不是使用两个事件,并使用sender对象:

private void dateTimePicker_KeyDown(object sender, KeyEventArgs e)
{
    var dtp = sender as DateTimePicker;
    if (e.KeyCode == Keys.Enter)
    {
        if (dtp?.Name[dtp.Name.Length - 1] == '1')
            dateTimePicker2.Focus();
        else dateTimePicker1.Focus();
    }
}

Just don't forget to change the value of the KeyDown event in the properties window of the both DateTimePickrs to point to this event. 只是不要忘记在两个DateTimePickrs的属性窗口中更改KeyDown事件的值以指向此事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM