Navigation in Windows Forms using enter key - c#

I have textboxes in my Windows Forms application, and I want that when the user presses the ENTER key then the cursor goes to the next textbox.
How do I do this?
Is this a good habit or shall I avoid it? Actually the users are very much prone and have adapted and have become habitual of pressing ENTER key for navigation between textboxes and buttons. So, for them I need to do this.
Please help me with the complete code using two text-boxes as an example.

I would say the nicest way is to create a user control that inherits from TextBox and then override the OnKeyPress method to capture enter and send a tab. Focus will then be given to the next TabIndex on the form, just as though a tab had actually been entered.
The code below does exactly that:
public partial class CustomTextbox : TextBox
{
public CustomTextbox()
{
InitializeComponent();
}
protected override void OnKeyPress(KeyPressEventArgs e)
{
if (e.KeyChar == '\r')
{
e.Handled = true;
SendKeys.Send("{TAB}");
}
}
}
You could also put similar code in the KeyPress event handlers for your controls but this saves a lot of duplicate code and unnececessary event handler.
As for whether this is good practice - I would say in general, no, changing the default behaviour of forms is never a good idea, but of course, if this is what your users want and expect, then it is their decision.

This is a bad idea. The standard UI is for TAB to move between input fields. You make your app less useable when you elect not to follow well known standards. These standards are what makes UI intuitive.

Yes, it depends on you
For a sample, you can place 4 textbox on the form and use the following code
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
textBox2.Focus();
}
}
private void textBox2_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
textBox3.Focus();
}
}
private void textBox3_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
textBox4.Focus();
}
}
It might help you.
Happy coding...

For example you could trap OnKeyUp event, check if it is RETURN and process source control to use Focus() to next control...

Yes you can fire the KeyDown or KeyUp event on a TextBox. To check whether it was the enter key, you can do the following:
//e is the KeyEventArgs from the event.
e.KeyCode == Keys.Enter
Then, if he has pressed the enter key, you can do:
System.Windows.Forms.Control.SelectNextControl();
To set the order of your controls, in Visual Studio look for this little icon:
http://i.stack.imgur.com/nZWLO.png
Click it, and you'll go into tab ordering mode, as I like to call it. Just click the controls in the order you wish them to be and after you're done, click the little icon again. Presto!
Now whether that is a good idea of not, completely depends on how used to it your end users are. If they have always used it like this, and you give them something that doesn't fit into their mind model, they are going to say your software is broken.
Always always always try to emulate what processes the user already has in place in their head.
Read this if you have the time, it's a really light and very good read:
http://www.joelonsoftware.com/uibook/fog0000000249.html

I think the best way would be to:
1) assign each textbox's TabIndex attribute incrementally (first is x, next is x+1 etc).
2) capture on the OnKeyUp event on the whole form, check the argument to see if the key was RETURN
3) focus the next textbox using its TabIndex. Or simulate the TAB key.
This code should work:
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
GetNextControl((TextBox)sender, true);
}
}
This way you end up writing only one function, and you can have as many textboxes as you want.

Related

How to switch to a next "Entity" (Example TB or MaskedTB) on the form with a specific key press

I am trying to find a solution to replicate what tab does when you are focused on a specific TextBox or MaskedTextBox, I already set my TabIndexs in order through Properties in VS
FormaNalaza is a form
private void FormaNalaza_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
//Switch to the next TabIndex Entity
}
}
This was my solution but I couldn't figure out how to change the focus to the next Entity in the form
I tried SelectNextControl(*The starting Entity*, 1, 0, 0, 0)
EDIT
Form Events
DateTimePicker Events (Its the first DataBox in the form...)
Code (2nd one works when it focused on the DTP)
IDK why but I am guessing it could be because from the start of the form there is a focus on a TB instead of the form but still that explanation is so stupid but if it works ill use it. It will take me 20min to generate methods and call a function that executes the code you provided...
keep in mind this is .NET Framework and as far as i know, it's old. I am guessing that you are using .NET Core
Simple Implementation:
private void FormaNalaza_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
//Switch to the next TabIndex Entity
SendKeys.Send("{Tab}");
}
}
Tab Order
Output:
Add it to the event:
The tab key does this automatically, so if you are ok with pressing tab instead of enter, you can do that. Changing the TabIndex property of your entities will change the order in which tab will switch between them.

How can I make my Form visible/invisible by pressing insert?

I'm trying to find out how to making my form invisible when I press insert and when I press insert again it makes the form visible. I try to find out how, but no one seems to have what I am looking for.
A simple example how you can manipulate Form's visibility by handling the Insert key down:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
// Don't forget to enable Form.KeyPreview in order to receive key down events
if (e.KeyCode == Keys.Insert)
{
Visible = false;
}
}
}
You can set Visible back to true to make it visible. However, you will not be able to do this, because Form became invisible and doesn't receive key down events anymore. In this case you can try to set the global hotkey using, for example, the GlobalHotKey library described here. Note also, that it doesn't make sense to set a single key (e.g. Insert) as global hotkey as in most cases system or another application will capture it.
You can do this:
private void InfoForm_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Insert) Opacity = Opacity == 0 ? 1 : 0;
}
For this to work you need to turn on the Form's KeyPreview property!
But turning visiblity back on (or to be precise turning off opacity) will only work if no other program has received focus in the meantime.
If that might happen you need to set a global keyboard hook; make sure to pass the Insert key back on or else many other programms will no longer work right.. All in all I would not recommend it..
I'm not sure when the whole idea might make sense. One answer could be to show or hide a popup data window that is only meant to show some additional information popping up from a base data window.
In that case you could simply close the window whenever it gets deactivated:
private void InfoForm_Deactivate(object sender, EventArgs e)
{
this.Close();
}

C# Keyboard button used to trigger a method

I'm writing a Hangman program in C# and when I press a keyboard button I want the button on the form to be clicked. Where should I write this? In form1.load()?
No, you should select the Form on which you want the event to be triggered, then go to the properties pane, select the event tab and go down to KeyPress event, double click it and add some code.
Normaly something like this would do what you want, just google the KeyChar value to determine the keyPress you want to control, you can add more if statements:
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)13)
{
Button1.PerformClick();
}
//Other if statements if you want to keep an eye out for other keyPresses
}
[edit] I just remembered you might be also considering the shortcuts, in wich case the Button1.Text property should be marked &Button1, this way the "B" would be underlined and accept the alt+B shortcut to execute the button click event.
The & symbol is set before the letter you want for the shortcut, make sure you dont use the same letter for various buttons.
You wouldn't write the code in Form.Load() if you want it to happen in response to a keyboard event. That event occurs (and the code inside of it is executed) when your form first loads (appears on screen).
How about handling the KeyPress event and writing the code in that method, instead? Your form has one of those events, too.
Sample code:
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
Button1.PerformClick();
}
The PerformClick method will generate a Click event for a Button control. You can handle that Click event in a similar way:
private void Button1_Click(object sender, EventArgs e)
{
// do something in response to the button being clicked
// ...
MessageBox.Show("Button clicked!");
}
If this event-handling stuff is confusing to you, make sure that you pick up a good book on programming in C# and/or the .NET Framework so that you learn it well. It's very important and not something to skip!
You have to enable KeyPreview property on the form, then you have to implements the KeyPress event directly on the form :
Form1.KeyPress +=new KeyPressEventHandler(Form1_KeyPress);
private void Form1_KeyPress(object sender, KeyPressEventArgs e) {
if(e.KeyCode == someKey) {
button1.performclick();
}
}
private void Form_KeyDown(object sender, KeyEventArgs e)
{
if(e.KeyCode == Keys.Left)
{
// Do your hang job
Button_Click(sender, EventArgs.Empty);
}
}
You need to subscribe to the events of interest and process them after. But before you need to read and study how to do that. It's a not a difficult issue in C#.
http://msdn.microsoft.com/en-us/library/ms171534.aspx
One time subscribed to the events create a function that you can call from button click and from keydown.

Avoid beep on pressing enter in numeric up down dialog

I have some numeric up/down controls in a c# application. Whenever I press enter on one of these, the computer sounds a beep. How do I prevent this from happening?
This seems to be a common problem, but I'm unable to find an answer that is complete enough for me to be able to make it work. Pehrhaps a stackoverflow quality answer would be useful.
In general, you can just suppress the KeyPress event on the KeyDown event:
private void numericUpDown1_KeyDown(object sender, KeyEventArgs e) {
if (e.KeyCode == Keys.Enter) {
e.SuppressKeyPress = true;
}
}

How to mark a pushbutton as a default for Enter key on form elements?

I have a Windows Mobile application in C#.
I have a couple of fields on the form, and when I hit enter I want the form submitted.
Is there a way to mark a pushbutton as default?
Also how can I make so the Down key moves the focus into the next field? Tab-order is not respected?
You can have a method that you link as the KeyDown event on all the controls from that form. In that you check if the KeyCode is Enter then you call the Submit method.
private void control_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
Submit();
}
Same thing, in the KeyDown method you handle the DownArrow key. Im not sure if you have the System.Windows.Forms.Control.SelectNextControl() method in the Compact Framework, but if you don't have it you can easily build something like that by yourself.

Categories