C#dateTimePicker Focus不起作用

时间:2017-10-17 13:40:04

标签: c# winforms

在我的C#Windows窗体应用程序中,我想通过按 Enter 键在两个dateTimePickerdateTimePicker1dateTimePicker2)之间导航。
Form打开焦点dateTimePicker1并按 Enter 键然后关注dateTimePicker2并按输入键焦点 dateTimePicker1 < / KBD>。

我正在尝试以下代码,但它不起作用:

private void dateTimePicker2_Enter(object sender, EventArgs e)
{
   dateTimePicker1.Focus();
}

4 个答案:

答案 0 :(得分:3)

输入控件按Tab键更改焦点或点击其中时,会触发Enter Event。如果您想收听输入密钥,则需要使用KeyDown Event

事件处理的实现如下所示:

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

答案 1 :(得分:1)

试试这个

private void dateTimePicker1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == (char)Keys.Enter)
    {
        dateTimePicker2.Focus();
    }
}

private void dateTimePicker2_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == (char)Keys.Enter)
    {
        dateTimePicker1.Focus();
    }
}

答案 2 :(得分:0)

Enter事件不代表按Enter键,表示用户将焦点更改为控件。

https://msdn.microsoft.com/en-us/library/system.windows.forms.control.enter(v=vs.110).aspx

答案 3 :(得分:0)

您应该使用KeyDown事件

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