KeyDown event is not firing when pressing enter in an UserControl - c#

I have a UserControl for an application and with a textbox. When pressing enter in this textbox a button should be activated (basically pressing 'Ok' via pressing Enter instead of clicking the button manually with the mouse).
So I added a KeyDown event to my textbox and implemented the following code:
private void txtSearchID_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter && !txtSearchID.Text.Equals(string.Empty))
{
button_Click(null, null);
}
}
But when I wanted to test this nothing happened when pressing Enter. Strangely enough in addition to that the event does not even get fired when pressing Enter but with every other key. Am I missing something?

This is because, when a key is pressed it will go to the control which has focus on the form, as the KeyPreview property of Form is set to False by default. You change the event like this
Change to KeyUP event,
private void txtSearchID_Keyup(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter && !txtSearchID.Text.Equals(string.Empty))
{
button_Click(null, null);
}
}

Related

MessageBox does not suppress keyboard Enter key

I have a button which, on Click event I made some validations upon some TextBoxes in my Form.
If a TextBox does not pass the validation, then I force the Focus to it (user must enter some characters in that TextBox). My TextBox class already have some code to go to the next control if user will press Enter key.
MyTextBox.cs class
public class MyTextBox : TextBox
{
public MyTextBox(){
KeyUp += MyTextBox_KeyUp;
KeyDown += MyTextBox_KeyDown;
}
private void MyTextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
// This will suppress Blink sound
e.SuppressKeyPress = true;
}
}
private void MyTextBox_KeyUp(object sender, KeyEventArgs e)
{
if ((e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Return))
{
// This will go to the next control if Enter will be pressed.
SendKeys.Send("{TAB}");
}
}
}
Form's button click event:
private void BtnPrint_Click(object sender, EventArgs e){
// txtName is based on MyTextBox class
if(txtName.Text.Length == 0){
MessageBox.Show("Name field could not be empty! Please fill the Name!", "Error Message",
MessageBoxButtons.OK, MessageBoxIcon.Error);
// If I Click the OK button, txtName will stay focused in the next line,
// but if I press Enter key, it will go to the next control.
txtName.Focus();
return;
}
// Some other validations ...
// Calling printing method ...
}
How do I stop the loosing focus on my textboxes when user hit Enter key in that MessageBox?
A MessageBox can cause re-entrancy problems in some occasions. This is a classic one.
In this specific case, when the Enter key is pressed to send a confirmation to the dialog, the KeyUp event re-enters the message loop and is dispatched to the active control. The TextBox, here, because of this call: txtName.Focus();.
When this happens, the code in the TextBox's KeyUp event handler is triggered again, causing a SendKeys.Send("{TAB}");.
There are different ways to solve this. In this case, just use the TextBox.KeyDown event to both suppress the Enter key and move the focus:
private void MyTextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
e.SuppressKeyPress = true;
SendKeys.Send("{TAB}");
}
}
Also, see (for example):
Pushing Enter in MessageBox triggers control KeyUp Event
MessageBox causes key handler to ignore SurpressKeyPress
as different methods to handle similar situations.

Keypress event stuck in infinite loop

I have a button that when pressed 'enter' would display a MessageBox and if you pressed enter again to close the MessageBox, it would go into an infinite loop. How do I ignore firing multiple key up event on the MessageBox?
this.okButton.KeyUp += new KeyEventHandler(this.okButton_KeyUp);
private void okButton_KeyUp(object sender, KeyEventArgs e)
{
if (e.Handled) { return; }
if (e.KeyCode == Keys.Enter && okButton.Enabled)
{
okButton_Click(null, null);
e.Handled = true;
}
}
private void okButton_Click(object sender, EventArgs e)
{
MessageBox.Show("Hello World", "", MessageBoxButtons.OK);
}
This is quite the desired behavior. What happens is,
During the Key Down event, Message Box gets closed.
During Key Up event, the Message Box is opened again.
What you can do here is remove the KeyUp event of Button and instead rely on Click event directly. Everytime you click Enter with focus on Button, the Click event would fire.
This will ensure you get the desired behavior.

Capturing Enter Key press on windows form not working

I have a user authentication form with username and password textboxes.There is an okay button that fires the code to validate the credentials.
I want the same code to get executed when the user hits Enter key anywhere on the form.
So i register for the keypress event like this
this.KeyPress += UserLogin_KeyPress;
private void UserLogin_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)13)
{
MessageBox.Show("enter");
}
}
This event is not triggered at all.What i'm i doing wrong?
Try setting the property keypreview to true and changing to keydown instead since KeyPress don't support e.Keycode:
private void UserLogin_KeyPress(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
MessageBox.Show("Enter");
}
}
Try this:
private void UserLogin_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
MessageBox.Show("enter");
}
}
As mentioned, set form.KeyPreview = true so that most key events will be given to the form before the controls.
However, note that this doesn't always work, and some controls will still "steal" certain key presses anyway. For example, if a Button has focus, then an Enter keypress will be used by the button to activate it, before you get a chance to see it, and since it counts as having been "handled", you never get to see the keypress.
The workaround I use for this is to set focus to something that I know will not steal the enter key press, for key presses that occur leading up to the enter key press. So, if the pressed keys are <1><2><3><4><ENTER> then the 1-4 keys all set focus to something that is not a button (usually, the textbox where I am displaying the resulting text), and then when <ENTER> is pressed, it should make it to your form's event handler (as long as KeyPreview == true).
It's only looking at the form. Controls on the form also need to be wired in.

Button KeyPress Not Working for Enter Key

I have a button for which I set the KeyPress event.
this.myButton.KeyPress += new KeyPressEventHandler(this.myButtonEvent_keypress);
private void myButtonEvent_keypress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Return || e.KeyChar == (char)Keys.Space)
{
// do something
}
}
Now whenever the Space key is pressed, I get the event triggered. This part works fine.
But for some reason, the Enter key press is not triggering the KeyPress
event. Also Alt, Ctrl, Shift are not working.
How can I make the button receive Enter key press?
UPDATE:
I tried below too without any luck
this.myButton.MouseClick += new MouseEventHandler(myButton_Click);
When a Button has focus and you press Enter or Space the Click event raises.
So to handle Enter or Space it's enough to handle Click event and put the logic you need there.
So you just need to use button1.Click += button1_Click;
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("Clicked!");
}
If you really want to know if Enter or Space was pressed, you can hanlde PreviewKeyDown event:
private void button1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
if(e.KeyCode== Keys.Enter)
{
MessageBox.Show("Enter");
}
if (e.KeyCode == Keys.Space)
{
MessageBox.Show("Space");
}
}
Enter and space can be handled using click event.
this.myButton.Click += new EventHandler(myButton_Click);
The Button control in WinForms will eat Enter, Space, Tab, ESC, and a few other special key's press events. One method to intercept these events is to override Control.ProcessDialogKey. Or you can override IsDialogKey to say if a key should be handled as a special case.
A another option is to set KeyPreview = true on you parent Form. Then you can handle all KeyPress events at the Form level and use Form.ActiveControl if you need to see what control has Focus

keydown event with keys.Enter and keys.Tag

I'm using some richTextBoxes in one page of my form, in keyDown of richTextBoxes, i wrote if Ctrl+Enter is pressed, sendKeys the Tab key so the next one get focus, and I also have a keyDown event on whole form, so when user press Ctrl+Tab, selected page change to next page
problem is, when i press Ctrl+Enter on the richTextBoxes, keyDown of form with Ctrl+Tab happens and tab changes, why it sees enter and tab alike ?
Sorry for my bad grammar, and thanks for your effort
keyDown event of Main Form:
private void Main_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Tab && e.Control)
{
//code for changing the tabs
}
}
keyDown event of richTextBoxes:
private void txtControl_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.Enter)
{
SendKeys.Send("{Tab}");
e.Handled = true;
e.SuppressKeyPress = true;
}
}
Usually, when you press a key, the focused control receives the key pressed. You could change a bit of this flow setting the Form.KeyPreview property to True. With this setting the Form receives the key pressed before the focused control.
You are messing with this 'normal' flow trying to insert a fake TAB key while you are processing the KeyDown event that has reached the RichTextBox keydown event handler. You suppress the CTRL+ENTER key but, at the exit of the event, the TAB key is received by the form with the Control bit still set and, as far as I know, there is no easy way to reset this bit, hence you process a CTRL+TAB in your form keydown.
Fortunately all of this is not needed, you set the next control in tab order line simply with
private void txtControl_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.Enter)
{
Control current = sender as Control;
this.SelectNextControl(current, true, true, true, true);
e.SuppressKeyPress = true;
}
}
The call to the form method SelectNextControl gives you a lot more control on what should happen and doesn't insert a fake TAB key in the keyboard processing.
You send tab SendKeys.Send("{Tab}"); on keydown. The modifier is stil CTRL. Than the keydown of the MainForm in focus catches Tab. Stop sending SendKeys.Send("{Tab}");?

Categories

Resources