MessageBox does not suppress keyboard Enter key - c#

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.

Related

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 is not firing when pressing enter in an UserControl

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);
}
}

How can I override the default button on a form when focus is in a TextBox

I have a winform form which has typical OK and Cancel buttons.
The OK button is set as the default button. When the user presses the ENTER key, the form is closed.
The form also has a text box which has a Search button beside it. The text box allows the user to enter search text and the Search button initiates the search function.
I would like the user to be able to press the ENTER key when the text box has the input focus and have the search function activate.
The problem is that the form is grabbing the ENTER key event before the text box's handler gets it.
EDIT: I've tried using the following event handlers, but they never get hit, and the form closes when the Enter key is hit:
private void txtFilter_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
Search();
e.Handled = true;
}
}
private void txtFilter_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
Search();
e.Handled = true;
}
}
I've also tried enabling the KeyPreview property on the form and implementing a KeyDown event handler for the form, but the Enter key never seems to cause any of these to be hit.
What is the best way to accomplish this?
Try handling the Enter and Leave events of the TextBox to clear out your form's AcceptButton property:
private void txtFilter_Enter(object sender, EventArgs e) {
this.AcceptButton = null;
}
private void txtFilter_Leave(object sender, EventArgs e) {
this.AcceptButton = closeButton;
}
Then you can just process your KeyUp event as your want:
private void txtFilter_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
Search();
}
}
Add a KeyDown event handler to the textBox and then add this to it
if (e.KeyCode == Keys.Enter)
{
btnSearch.PerformClick();
}

Categories

Resources