Windows Forms - Enter keypress activates submit button? - c#

How can I capture enter keypresses anywhere on my form and force it to fire the submit button event?

If you set your Form's AcceptButton property to one of the Buttons on the Form, you'll get that behaviour by default.
Otherwise, set the KeyPreview property to true on the Form and handle its KeyDown event. You can check for the Enter key and take the necessary action.

private void textBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
button.PerformClick();
}

You can designate a button as the "AcceptButton" in the Form's properties and that will catch any "Enter" keypresses on the form and route them to that control.
See How to: Designate a Windows Forms Button as the Accept Button Using the Designer and note the few exceptions it outlines (multi-line text-boxes, etc.)

As previously stated, set your form's AcceptButton property to one of its buttons AND set the DialogResult property for that button to DialogResult.OK, in order for the caller to know if the dialog was accepted or dismissed.

You can subscribe to the KeyUp event of the TextBox.
private void txtInput_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
DoSomething();
}

The Form has a KeyPreview property that you can use to intercept the keypress.

Set the KeyPreview attribute on your form to True, then use the KeyPress event at your form level to detect the Enter key. On detection call whatever code you would have for the "submit" button.

Simply use
this.Form.DefaultButton = MyButton.UniqueID;
**Put your button id in place of 'MyButton'.

if (e.KeyCode.ToString() == "Return")
{
//do something
}

Related

Backspace key to return previous form

I want to return to previous form in C# using backspace key.
I am using KeyDown event on form to check for backspace key . but the form is not detecting any key down event.
How can I achieve this?
private void History_P_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData.ToString() == "Back")
MessageBox.Show("Back button pressed");
}
where History_P is form name.
You need to enable the KeyPreview property on the Form.
With this property the key being pressed (all KeyUp, KeyDown, KeyPressed events) will first be caught by the Form and is then passed on to the control that is focused at that moment, unless you set the KeyPressEventArgs.Handled to true.

Validating Data In A WinForm

I have created a dialog box in my WinForms application. This has many text boxes and ok/cancel buttons. When the user clicks ok, I only want the dialog box to close if all entries are valid. I can see how to do this with the "Validating" events for each control separately. That is fine. But these only seem to fire when a control loses focus. However, empty text boxes in my dialog are also invalid input which means the user may never have focused on that control. I would prefer to just validate all controls on clicking OK.
I can't work out how to do this though. Overriding the onclick of the OK button doesn't seem to have an option for stopping the window from closing. The Form IsClosing event does by setting Cancel = true. But this doesn't seem to be able to distinguish between whether the OK or Cancel button is clicked. Obviously if the cancel button is clicked I don't care about validation and want to allow the form to close regardless.
What is the best approach for doing this?]
Update:
I already had CausesValidation set to true on both my form and ok button but my validation event does not get fired when I click the ok button. I mention this as it was suggested as a solution below.
Please select the form > Set the property CausesValidation to true
Select OK button and again set property CausesValidation to true
and then it will take care of all the validations.
Important points:
1) You must mention e.Cancel=true in all the validating eventhandlers
2) If your buttons are in panels then you must set panels (or any parent control's) CausesValidation property to true
Edit:
3) Validate fires just before loss of focus. While pressing Enter will
cause the default button to Click, it doesn't move the focus to that
button, hence no validation event will be fired if you have set forms AcceptButton Property to OK button
First make sure to cancel the validation when any of the textboxes have validation errors. For example:
private void nameTextBox_Validating(object sender, CancelEventArgs e) {
if (nameTextBox.Text.Length == 0)
{
e.Cancel = true;
return;
}
}
Now add the following code to the beginning of the ok button action:
if (!ValidateChildren())
return;
This will trigger the validation event for all controls on the form,
You can also use this simple code. just introducing a simple Boolean variable named hasError can do the job.
public partial class Form1 : Form
{
private bool hasError;
public Form1()
{
InitializeComponent();
}
private void OkBtn_Click(object sender, EventArgs e)
{
errorProvider1.Clear(); hasError=false;
if (ValidateTxt.Text.Length == 0)
{
errorProvider1.SetError(ValidateTxt, "must have a value");
hasError=true;
}
if (!hasError)
{
//Do what you want to do and close your application
Close();
}
}
private void CancelBtn_Click(object sender, EventArgs e)
{
Close();
}
}

KeyDown not picking up 'Return' key C#

private void idTextEdit_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Return)
{
e.Handled = true;
SearchButtonClick(sender, EventArgs.Empty);
}
}
I have a text box where this code check fires for every single keypress except for the Enter/Return key which for some reason does nothing. The cursor that is active on the textbox disappears, so I'm thinking it changes focus before the keydown event can fire but I'm not sure. How can I get the return key to stop deselecting the box and register as a keypress. Also there is no other code that would set the enter key to have a different functionality and it's a pretty simple one text box screen for testing.
If you have an AcceptButton set then you'll get the behaviour you are seeing.
I tried your code with my sample form and it worked as expected.
I then set the AcceptButton to one of the buttons and the text box stopped responding to the Enter. Setting AcceptsReturn on the text box had no effect.
Set the AcceptsEnter property to true

How to intercept the TAB key press to prevent standard focus change in C#

Normally when pressing the TAB key you change the focus to the next control in the given tab order. I would like to prevent that and have the TAB key do something else. In my case I'd like to change focus from a combobox to a completely different control. I can't do this by setting the tab order. I need to do this programatically. Any idea how? It seems like the KeyDown and KeyPress events can't handle TAB key correctly.
Thanks.
Override ProcessDialogKey or ProcessTabKey on your Form and do the logic you want depending on which control is focused.
Based on JRS's suggestion of using the PreviewKeyDown event, this sends the key press through to the control:
private void textBox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
if (e.KeyCode == Keys.Tab)
e.IsInputKey = true;
}
Then you can handle the control's KeyDown event if you want to customise the behaviour:
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Tab)
{
MessageBox.Show("The tab key was pressed while holding these modifier keys: "
+ e.Modifiers.ToString());
}
}
TextBoxBase alternative
If the control is derived from TextBoxBase (i.e. TextBox or RichTextBox), with the Multiline property set to true, then you can simply set the AcceptsTab property to true.
TextBoxBase.AcceptsTab Property
Gets or sets a value indicating whether pressing the TAB key in a multiline text box control types a TAB character in the control instead of moving the focus to the next control in the tab order.
Override the control's LostFocus event see link below for examples:
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.lostfocus.aspx
Since I am building a UserControl, I ended up using the PreviewKeyDown event on the control. This avoids having to handle key press events on the host form.
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.previewkeydown.aspx
You can try this code on your KeyDown event:
if (e.KeyCode == Keys.Tab) {
//your logic
e.SuppressKeyPress = true;
}
If the button clicked is Tab, then do any custom logic you want, then call SuppressKeyPress to stop the KeyPress event from firing and invoking the normal Tab logic for you.

Handle windows calls with in .net program?

I have an application which runs on click of tray icon in windows( developed in C#). I want to minimise the application on click of escape button. how do i accomplish this ?
Thanks in advance,
Ravi Naik.
There are several ways to achieve this. One is to set the KeyPreview property of the form to true, and have the following KeyDown event handler:
private void Form_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape)
{
this.WindowState = FormWindowState.Minimized;
}
}
Another approach is to have a button that will minimize the form in its Click event, and point that button out in the form's CancelButton property.
You need to override IsInputKey and return true for handling the escape. Then you can add the handler for KeyDown event and do the minimize operation.
If on the click of a particular button you want the application to minimize to tray then take a look at NotifyIcon class.

Categories