How do I highlight RichTextBox Text in WinForm [duplicate] - c#

I have a TextBox in my form and I added this event on it:
private void txtValue_KeyDown(object sender, KeyEventArgs e)
{
MessageBox.Show(e.KeyData.ToString());
}
But it always prints the upper case of the letter even though I entered a lower case letter in the textBox. Please see image below:
How should I get the right display? Thanks...

KeyDown and KeyUp use KeyEventArgs, which exposes the Keys enum via the KeyData property. The enum does not have representation for lower-case alphabetic values.
http://msdn.microsoft.com/en-us/library/system.windows.forms.keys.aspx
The KeyPress event allows you to get the actual character of the key pressed via KeyPressEventArgs.KeyChar.
private void txtValue_KeyPress(object sender, KeyPressEventArgs e)
{
MessageBox.Show(e.KeyChar.ToString());
}

If you handle the KeyPress event instead, you can examine the KeyChar property of KeyPressEventArgs to get the correct case.

Related

Only do event after complete

How to do the event handling when the user presses the ENTER key or leaves the focus on the particular textbox? I tried for KeyChanged event, but it will keep updating the number instead of only once when complete.
private void txtNumber_TextChanged(object sender, EventArgs e)
{
txtNumber.Text = double.Parse(txtNumber.Text).ToString("F2");
}
There are a few issues with the posted code. One issue is that doing the formatting each time the user “types” a character is going to be awkward for the user. In addition, if the user presses the “Enter” key, the event txtNumber_TextChanged is not going to fire. I assume you may already know this.
Next, when getting input from users, it is imperative that you check the input for valid numbers BEFORE calling the parse method…Example, the line of code…
double.Parse(txtNumber.Text).ToString("F2");
Will FAIL and crash the program if the text in the text box… txtNumber.Text is NOT a valid double.
You should always assume the user is going to make a mistake and you don’t want your code to crash when they do.
Therefore I suggest using the double.TryPasre method to avoid these possible crashes, calling this method will NEVER throw an exception and will make validating the number easier.
To get what you want I recommend you wire up three (3) events for the text box…
The Leave event, this is used to format the text, when the user leaves the text box, like when they click on another control.
Next is the PreviewKeyDown event, this is used when the user presses the “Enter” key.
And one extra event to help the user ONLY add numbers and one dot. The KeyPressed event is wired up and will ignore any pressed keys that are not numbers or the dot (period). Also, it will only allow one period, if the user tries to add a second decimal place, it will be ignored.
Bear in mind, the key pressed event helps by preventing the user from “typing” alpha text into the text box… however, the user can still paste text. Fortunately, since we are using the TryParse method, when the pasted text is an invalid number, the try parse will simply return “0.00” and NOT crash the code.
private void txtNumber_Leave(object sender, EventArgs e) {
double.TryParse(txtNumber.Text.Trim(), out double number);
txtNumber.Text = number.ToString("F2");
}
private void txtNumber_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) {
if (e.KeyCode == Keys.Enter) {
double.TryParse(txtNumber.Text.Trim(), out double number);
txtNumber.Text = number.ToString("F2");
}
}
private void txtNumber_KeyPress(object sender, KeyPressEventArgs e) {
if (!char.IsControl(e.KeyChar) // <- key pressed is not a control key
&& !char.IsDigit(e.KeyChar) // <- key pressed is not a digit (number)
&& e.KeyChar != '.') { // <- key pressed is not a dot (.)
e.Handled = true; // <- if its not a control key, digit or dot... then ignore it
}
// only allow one decimal point - if there is already a dot, then ignore the second one
if (e.KeyChar == '.' && txtNumber.Text.IndexOf('.') > -1) {
e.Handled = true; // <- if there is already a dot in the text... then ignore it
}
}
Formatting a text value in a TextBox must be done once the input is already done.
TextChanged, occurs when the Text property value changes. So this is not ideal.
The only event you can rely on.
LostFocus, occurs when the control loses focus. You can sheck some info when control change focus.
private void textBox1_LostFocus(object sender, System.EventArgs e)
{
// Code here
}
Sometimes we wanted the format to be changed once we click something on the keyboard, so here are the possible events for that.
The non-character keys do raise the KeyDown and KeyUp events.
KeyDown, occurs when a key is pressed while the control has focus.
KeyUp, occurs when a key is released while the control has focus.
KeyPress, occurs when a character. space or backspace key is pressed while the control has focus.
Note: When using the KeyPress you need to also consider if the Form is the one handling the input events first or not, check the Remarks here.
private void textBox1_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e)
{
if (e.KeyCode == Keys.Return) // You can also use: e.KeyValue == 13
{
// Do your code here
}
};

Raise a Text box event when fourth digit is entered

I am working on a c# windows forms application and I have a text box which accepts a maximum of four character for which I am trying to raise am event when fourth character.
I tried to include it in KeyPress event but to raise the event I had to press a key after all the four characters are entered
private void txtFourC_KeyPress(object sender, KeyPressEventArgs e)
{
if ( txtFourC.TextLength == 4)
{
//code here
}
}
Is there a better way to do this may be other than Key_Press
To limit the maximum number of characters that users can type or paste into the TextBox, it's enough to set MaxLength property.
If you don't want to limit the user, but you want to be notified when the user entered more than 4 characters, handle TextChanged event and check for TextLength property to know length of text in the control.
Or use the event to f.e. jump to the next field after the 4th digit is typed.
So use the TextChanged event and check for TextLength property to know length of text in the control and activate the next field.
If the purpose is to restrict input to maximum 4 characters then its best to set MaxLength property. txtFourC.MaxLength=4
However, if you want to show message when 4th character is typed in then you may use KeyUp event instead KeyPress.
private void txtFourC_KeyUp(object sender, KeyEventArgs e)
{
if(txtFourC.Text.Length ==4)
{
MessageBox.Show("Reached max length");
}
}
private void txtFourC_TextChanged(object sender, KeyEventArgs e)
{
if(txtFourC.Text.Length == 4)
{
//do your control here.
}
}

Default editing commands not working in TextBox when filtering KeyPress

I have a textbox in my winform in which after puting a validation using regex on keypress event, the default functionalities like copy paste etc of the textbox is not working.
How can i handle this?
Regex used code
private void textbox_keypress(object sender,keypresseventargs e)
{
var regex= new regex(#"^[0-9,]*$");
if(!regex.ismatch(e.keychar.tostring()))
{
e.handled=true;
}
}
after removing the keypress event handler everything is working fine but i have to restrict user to enter comma separated number value and also copy paste delete backspace in that textbox.
The Ctrl-Commands don't work because you abort their entries. To avoid this you must either
check if the Ctrl-Key has been pressed. The KeyPress event doesn't tell you that. This example from MSDN shows you how to do it: You script the KeyDown event to set (or clear) a flag variable, which you can then test in the KeyPress. No, not exactly elegant imho, but that's how MS tells you to do it.. (Note that I have added the Backspace code \b, as it isn't covered by the Ctrl-check..)
bool ctrlPressed = false;
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
ctrlPressed = (Control.ModifierKeys == Keys.Control);
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!ctrlPressed)
{
var regex= new Regex(#"^[0-9,\b]*$");
if (!regex.IsMatch(e.KeyChar.ToString()))
{
e.Handled = true;
}
}
}
Or, if you want better control over which Ctrl-Keys are allowed, skip the whole flags-affair and instead simply include them one by one in the allowed keys-brackets like this for ^C, ^X, ^A, ^V ^Z etc..:
var regex= new Regex(#"^[0-9,\b\cC\cX\cA\cV\cZ]*$");
Here is the description from MSDN:
\cX Matches an ASCII control character, where X is the letter of the
control character. For example, \cC is CTRL-C.
On a side note: The old fashioned copy&paste commands of Ctl-Ins and Shift-Ins work as normal even in your original code.

Ignore KeyDown if the text of a RichTextBox won't change

I need to determine whether a key, when it is pressed, will change the control's text or not; I need to ignore key presses like Ctrl+Z or Esc, but I need to know which key was pressed if the text changed.
Is there any way to know that in the KeyDown event? Currently, I'm using a flag, set on KeyDown and checked on TextChanged, but I was wondering if there is a better way?
You're looking for Char.IsControl
private Keys lastKey = Keys.None;
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
lastKey = e.KeyData;
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (Char.IsControl(e.KeyChar))
{
e.Handled = true;//prevent this key press
Keys pressedKey = this.lastKey;
//Do your stuff with pressedKey here
}
}
You could catch the KeyPress event on the text box and if it is a valid key you would set e.handled = false and if it was a bad key you would set e.handled = true.
example from: here
private void keypressed(Object o, KeyPressEventArgs e)
{
// The keypressed method uses the KeyChar property to check
// whether the ENTER key is pressed.
// If the ENTER key is pressed, the Handled property is set to true,
// to indicate the event is handled.
if (e.KeyChar == (char)Keys.Return)
{
e.Handled = true;
}
}
There are some keys which produce a Control char but they also change the text, for example BackSpace. They have another difficulty: if the textbox is empty, pressing them (for example BackSpace) doesn't change the text; so it breaks the previous rule. So Control characters are not naive to deal with and build a rule upon.
Moreover, consider Ctrl + C or Shift + Insert or similar cases. The 'C' key is somehow seductive; it is like pressing 'C' changes the text but if it was pressed with 'Ctrl', it actually didn't change the text. We should check the Modifiers.
Perhaps you can find other difficulties to deal with and I think the flag approach is good enough.

Always in upper case... (C# winforms)

I have a TextBox in my form and I added this event on it:
private void txtValue_KeyDown(object sender, KeyEventArgs e)
{
MessageBox.Show(e.KeyData.ToString());
}
But it always prints the upper case of the letter even though I entered a lower case letter in the textBox. Please see image below:
How should I get the right display? Thanks...
KeyDown and KeyUp use KeyEventArgs, which exposes the Keys enum via the KeyData property. The enum does not have representation for lower-case alphabetic values.
http://msdn.microsoft.com/en-us/library/system.windows.forms.keys.aspx
The KeyPress event allows you to get the actual character of the key pressed via KeyPressEventArgs.KeyChar.
private void txtValue_KeyPress(object sender, KeyPressEventArgs e)
{
MessageBox.Show(e.KeyChar.ToString());
}
If you handle the KeyPress event instead, you can examine the KeyChar property of KeyPressEventArgs to get the correct case.

Categories

Resources