0

In C# windows application to navigate all control of a Form (using Enter Key) I am using the below code:

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

N.B.: Form Property KeyPreview = True;

The above code works fine but when I am going to navigate between two dateTimePicker (dateTimePicker1, dateTimePicker2) pressing Enter Key. When Form open Focus on dateTimePicker1 and press Enter Key then Focus dateTimePicker2 and press Enter Key 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?

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.

Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
mr ali
  • 69
  • 2
  • 9
  • It's enough to use the first solution to navigate between all controls. What's the problem? – Reza Aghaei Oct 17 '17 at 19:00
  • I don't see a question either. It is a bad habit to get into, the Enter key just plays a very different role in a GUI. It is used to operate the default button of a window, the one selected by the Form.AcceptButton property. And to add lines to a RichTextBox and a multi-line TextBox. Very occasionally to solve a UX problem, the address box of a browser for example. Users are content to use the Tab key and the cursor keys to navigate. – Hans Passant Oct 17 '17 at 22:49

1 Answers1

1

You can subscribe your two DateTimePickers to the same event handler instead of using two events, and use the sender object:

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.

Salah Akbari
  • 39,330
  • 10
  • 79
  • 109