I have 2 input box on my form. If user enter data he can press enter to see if they are correct or in the other case messagebox will appear with error. Now i have small problem. When messagebox appears and user presses enter, msgbox disappear and immediately appear another one. I wanted to disappear, and let user change their data. How can i fix that?
I tried to fix that in that way: i added invisible textbox, when user press enter this textbox gains focus, if there is error msgbox appears and in the end sender gains focus.
code:
private void login(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
focus.Focus();
if (password.Password == "" || account.Text == "")
{
MessageBoxResult result = MessageBox.Show("Fill login and password.");
}
if(sender.GetType() == account.GetType())
((TextBox)sender).Focus();
else
((PasswordBox)sender).Focus();
}
}
Try setting e.Handled = true; to prevent propagating of the key press to your text box.
try this:
if (e.Key == Key.Enter && !string.IsNullOrWhiteSpace(txtPass.Text))
{
if (1 + 1 != 3)
{
MessageBox.Show("Wrong!!!");
txtPass.Clear();
txtPass.Focus();
}
}
Related
private void UserInputText_KeyDown(object sender, KeyEventArgs e)
{
if ((e.KeyCode == Keys.D4 && e.Modifiers == Keys.Shift) || (e.KeyCode == Keys.Add))
{
if (String.IsNullOrEmpty(UserInputText.Text))
{
MessageBox.Show("Bir sayı giriniz.");
UserInputText.Clear();
return;
}
if (double.TryParse(UserInputText.Text, out sayı1))
{
CalculationResultText.Text = sayı1 + " + ";
islem = "+";
UserInputText.Clear();
}
else
{
MessageBox.Show("Sadece sayı değeri girebilirsiniz.");
UserInputText.Clear();
}
}
}
I am coding a basic forms calculator. I am trying to trigger addition function and clear the textbox when textbox is focused and user presses "+" key. "if (String.IsNullOrEmpty(UserInputText.Text)) and else conditions work well. But if no Message boxes shows up as in the
if (double.TryParse(UserInputText.Text, out sayı1)) condition, the "+" character remains in the textbox as in the image. Thanks for help.
If I understand correctly, you want to first check the character that was typed in and if it's incorrect then you want to prevent this character from appearing?
If so, then you need to set e.Handled = true property when you want to prevent it.
This call tells the GUI element (your TextBox) that "I did all the checks for this event (i.e. KeyDown event), and I don't want you to contribute in handling of this event (i.e. normally the TextBox would try to add this character to its Text property, but you prevent it)".
Check out documentation on KeyEventArgs.Handled.
KeyPress event enables you to prevent any further changes in the TextBox.
You can do that thanks to Handled property of KeyPressEventArgs
private void UserInputText_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == '+')
{
UserInputText.Clear();
e.Handled = true;
}
}
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.
Take a simple messaging program, such as Steam friend conversation.
When you hit ENTER, the message is sent, and the message field is emptied.
When you enter CTRL/SHIFT + ENTER a newline is created. If your cursor is not at the end of the input text, then all the text appearing after your cursor will be sent to a newline.
Well, how do you accomplish such a feat ?
Furthermore, I'd like to know how to have the aforementioned features and also how to still be able to paste a multiline text into the message field.
For now, this is my code. It's something but does not get all the job done :
private bool ctrlOrShift = false;
private void MessageField_KeyDown( object sender, KeyEventArgs e )
{
if( e.Key == Key.LeftCtrl || e.Key == Key.LeftShift )
{
ctrlOrShift = true;
}
else if( e.Key == Key.Enter && ctrlOrShift != true && !MessageField.AcceptsReturn )
{
AsyncSendMessage();
}
else if( e.Key == Key.Enter && ctrlOrShift != true && MessageField.AcceptsReturn )
{
MessageField.AcceptsReturn = false;
}
else if( e.Key == Key.Enter && ctrlOrShift == true )
{
ctrlOrShift = false;
MessageField.AcceptsReturn = true;
MessageField.Text += System.Environment.NewLine;
MessageField.Select( MessageField.Text.Length, 0 );
MessageField.AcceptsReturn = false;
}
else
{
ctrlOrShift = false; // Canceled because follow-up key wat not ENTER !
}
}
The following scenarios occur :
Using CTR or SHIFT, I can create a new line in my TextBox :) ;
I cannot paste a multiline text from the Clipboard: only the first line will be pasted, nothing else :( ;
If I use CTRL + V to paste content, the MessageField_KeyDown event takes the CTRL hit is taken into account, therefore, if I press ENTER, message is not sent but a newline is created instead :/ (in a case where you would paste a content and send it right away) ;
If my cursor position is before the end of the input text, CTR/SHIT + ENTER will create a newline at the end of the text regardless of the cursor position :/
So, how can I tweak this code ? Thanks for the help !
The Result of the Solution is this:
Normal
After one SHIFT + ENTER
When you push ENTER it looks like in Normal only without text in the box
As mentioned in the comments you could use the AcceptsReturn and TextWrapping properties for a multiline textbox (like in steam).
Use Height = Auto for a better looking one (otherwise you only have one line and all other lines disappear)
XAML
for Textbox:
<TextBox HorizontalAlignment="Left" Height="Auto" Margin="10,10,0,0"
TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top"
Width="497" AcceptsReturn="True"
KeyDown="TextBoxKeyDown" PreviewKeyDown="TextBoxPreviewKeyDown"/>
Event Handler:
This is not that easy as i thought first :'D But i figured it out.
When you use the AcceptsReturn Property the Enter Key is Handeled by the AcceptsReturn. So if you push enter you will see a new line instead of a Send() if you programm is like this:
private void TextBoxKeyDown(object sender, KeyEventArgs e)
{
var textbox = sender as TextBox;
// This will never happen because the Enter Key is handeled before
// That means TextBoxKeyDown is not triggered for the Enter key
if (e.Key == Key.Enter &&
!(Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) &&
!(Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.LeftShift)))
{
// Send(textBox.Text)
textbox.Text = "";
}
}
So you need to implement the PreviewKeyDown eventhandler. Because in the PreviewKeyDown event handler the Event is routed through the (Parent)Elements.
Look at this Answer
Also note the e.Handled = true line. Otherwise the Enter is routed through the method to the AcceptsReturn and you will have 2 lines after the enter, but the Textbox is empty.
With this method the KeyDown Method is no longer needed!
private void TextBoxPreviewKeyDown(object sender, KeyEventArgs e)
{
// Enter key is routed and the PreviewKeyDown is also fired with the
// Enter key
var textbox = sender as TextBox;
// You don't want to clear the box when CTRL and/or SHIFT is down
if (e.Key == Key.Enter &&
!(Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) &&
!(Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift)))
{
textbox.Text = "";
e.Handled = true;
}
}
The pros of the Multiline Textbox is that you can copy and paste
+ you have no problems with CTRL pushed or not.
What do you think about it?
Hope it helps
I have a RichTextBox that i am searching text in and I want to be able to control what the enter key does when text is selected. I am able to use this if test below to call the method that I want, but my issue is after the method gets hit when the enter key is pressed it then moves the text to the second line and I want to be able to stop this from happening when the text is highlighted.
I test to check if the text is selected when enter is pressed.
if (IsTextSelected == true)
{
btnSearch_Click(sender, null);
}
You can listen to the PreviewKeyDown event like:
<RichTextBox PreviewKeyDown="RichTextBox_PreviewKeyDown"/>
and in the handler:
private void RichTextBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Return)
{
// DO YOUR WORK HERE and then set e.Handled to true on condition if you want to stop going to next line//
e.Handled = true;
}
}
My question somewhat relates to this question but the solution suggested is not working for me.
So here's my case.
I have a child form within an MDI parent. The form contains Tab control and a GridView in it.
I have added keyboard shortcuts within KeyUp event of the form itself. Now when user has selected one of the rows in Grid and hits Delete, I do MessageBox.Show() with YESNO buttons to confirm user's action.
Also, Form supports Enter (or Ctrl+O) key that if User hits it while record is selected from the Grid, it opens the Record in another child form for editing.
Here, Enter key is causing conflicts, as when I have that delete confirmation MessageBox open, and I hit "Enter", it does the delete operation but the same record is also opened in the child form for editing (this can obviously lead to NullPointers but I guess delete from Database occurs after the record is cached for opening).
As the solutions provided in the similar question I linked earlier, I tried setting a Form level flag which is set to true when MessageBox is opened and set to false when user clicks either of Yes or No keys, but I'm unsure if I'm setting flag at proper place in code or not.
PSA: I have Delete and Open as buttons on the form as well and thus I'm using same methods on Shortcuts.
Here's my KeyUp Event of Form
private void FormAnalystOpenReport_KeyUp(object sender, KeyEventArgs e)
{
if (((e.Control && e.KeyCode == Keys.O) || e.KeyCode == Keys.Enter) &&
!this.DELETE_CONFIRM_OPEN)
{
rtBtnOpen_Click(sender, e);
}
else if (e.KeyCode == Keys.Delete)
{
rtBtnDelete_Click(sender, e);
}
}
And following method to delete record
private void rtBtnDelete_Click(object sender, EventArgs e)
{
DataGridViewRow row = (DataGridViewRow)rtDataGrid.SelectedRows[0];
int delete_id = int.Parse(row.Cells[0].Value.ToString());
this.DELETE_CONFIRM_OPEN = true;
DialogResult feedback = MessageBox.Show(this,"Are you sure you want to delete selected record?", "Confirm Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if(feedback == DialogResult.Yes)
{
if (this.db.DeleteRecordById(delete_id)) //Would return true for successful delete of record, false otherwise.
{
//Code to reload Grid Data with updated Records list.
}
else
{
MessageBox.Show(this, "Failed to delete record!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
this.DELETE_CONFIRM_OPEN = false;
}
Thanks!
I think your problem is that messagebox works off a KeyDown event so when you return to your form the button is Down and you release it thus triggering your KeyUp.
try adding a keydown event to your form to set the deleteconfirm.
if ((e.Control && e.KeyCode == Keys.O) || e.KeyCode == Keys.Enter)
{
canDelete = true;
}