C# - Press Enter Key to move to next control on a Windows Form
Many times while working on Windoes forms we get into situation where we want to move to controls using ENTER key. To make it simple below is the detailed code. its very simple
1. Select the Form where this needs to be applied.
2. Set the Forms Key Preview Event.
3. Write the Keydown even for the Form.
4. Set the Code to fire the Tab control.
C# - Press Enter Key to move to next control on a Windows Form using single code
-------------------------------------
1. In the Form, Select Form--> Press F4 to open the Property box. or
Click on View Menu--> Property Window menu item.
2. This will open the Property box.
3. Look for property KEY PREVIEW and set it to TRUE.
This will make the form listener to all events we are performing on Controls. This is useful to avoid writing Lost Focus() code for each control.
4. Now here is the little code you need to write for Forms KeyDown event.
//Code to be pasted in your form. My Form name is frmNewInput. Change your code as appropriate formname.
private void frmNewInput_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
this.SelectNextControl(this.ActiveControl, true, true, true, true);
}
}
Note: Please dont use that (Control)sender instead of this.ActiveControl as this wont work because it wont understand which control to focus now. As you must be aware that SelectNextControl(..) is a in-built into .NET framework 3.5 so there is no hassle or performance issues.
You can freely use my code in yours and make your creations well.
Really Excellent one. This helped me a lot.
Thanks Nikesh