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.


Attachments

Comments

Guest Author: Abhirup19 Jun 2012

Really Excellent one. This helped me a lot.

Thanks Nikesh

Guest Author: bharat29 Oct 2012

thanks sir, i need it and i like it but i want to previous so what can i do ?
please response with bharat@macfuturetechsoft.in

Author: Nikesh Kumar Sinha30 Nov 2012 Member Level: Bronze   Points : 3

Hello Bharat,
thanks for the comment. For the Previous, you need to make a small change :

change the first bool Parameter to false. It will look below :

this.SelectNextControl(this.ActiveControl, false, true, true, true);

I tested it and it works well. Hope it will work for you too. Write to me in case you have any issue.

Regards,
Nikesh

Guest Author: Nikhil Jain14 Dec 2012

Thanks Nikesh

its very useful

-Nikhil Jain

Guest Author: Gopal28 Dec 2012

really nice1

Author: ketan Italiya02 Aug 2013 Member Level: Gold   Points : 0

it is very useful ..



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: