I am using the following code to extract the last character( the character just typed) using the following code
private string GetTypedChar()
{
string currentChar = "";
int i = rtfText.SelectionStart;
if (i > 0)
{
currentChar = rtfText.Text.Substring(i-1, 1);
MessageBox.Show(i+":"+currentChar);
}
return currentChar;
}
But this is giving me wrong results. If the word entered is "RS" the after pressing R the message box shows 1: (blank) then on typing S message box shows 2:R
How to achieve this?
to get the last entered character. You can handle the keyup event
private void richTextBox1_KeyUp(object sender, KeyEventArgs e)
{
char last = (char)e.KeyValue;
}
you can get the last character of your rich text box
string lastCharacter = rtfText.Text.SubString(rtfText.Text.Length - 1,1);
or
char last = rtfText.Text[rtfText.Text.Length - 1];
or
The important question is when you execute that code. Sounds like you subscribe to the 'KeyDown' event. By the time this event is raised, the key stroke has not yet been processed by the form --> So you don't see the change. You could use the KeyUp event. When this gets fired, your control has a changed context.
This will, however, not help you, if the new character is not the last one. The user could change the courser position and type a character. Then the new character is somewhere in the middle of the text. This can be solved by actually checking which key has been pressed. This information is in the KeyEventArgs parameter.
You could just eliminate GetTypedChar() altogether and subscribe to the KeyPress event.
Note that this won't give you the position of the character though, if you need that information.
private void richTextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
MessageBox.Show(string.Format("Last char typed: {0}", e.KeyChar));
}
Related
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
}
};
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.
}
}
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.
I have RichTextBox and I want to calculate the length of text entered in the KeyDown event. The problem is for characters in capital form I have to press Shift which is also getting calculated in the length. See the following code:
private void rtfText_KeyDown(object sender, KeyEventArgs e)
{
if (e.Modifiers != Keys.Shift)
{
var val = (char)e.KeyValue;
string _typed += val;
}
}
For texts like Win with capital W the length of _typed is shown as 4 where as it should be 3. How to solve this ? I wrote the above code to overcome this but now the length is shown as 2 instead of 3 because of suppressing Shift.
Just change your code to this:
private void rtfText_KeyDown(object sender, KeyEventArgs e)
{
if (!char.IsControl((char)e.KeyValue))
{
var val = (char)e.KeyValue;
string _typed += val;
}
}
that way if a control key is pressed you won't count it or aggregate it to your string.
(PS: control keys are shift, ctrl ...)
see this link: http://msdn.microsoft.com/fr-fr/library/18zw7440(v=vs.95).aspx
it lists the control characters and explains what exactly the method char.IsControl does
EDIT: actually there is quite a lot of situations where it won't work. Of course you can try to handle every specific situation (such as backspace, ctrl+V...) but the simplest way would be to use the TextLenght property and the TextChanged event
You should just get the TextLength property from the ritch text box directly:
var textLength = rtfText.TextLength
I have prevented numbers from being typed in text box using key down event. But when using Ctrl+V or pasting content through mouse, the numbers are being entered in the text box. How to prevent this? I have to allow all text to be pasted/typed except numbers.
On quite simple approach would be to check the text using the TextChanged event. If the text is valid, store a copy of it in a string variable. If it is not valid, show a message and then restore the text from the variable:
string _latestValidText = string.Empty;
private void TextBox_TextChanged(object sender, EventArgs e)
{
TextBox target = sender as TextBox;
if (ContainsNumber(target.Text))
{
// display alert and reset text
MessageBox.Show("The text may not contain any numbers.");
target.Text = _latestValidText;
}
else
{
_latestValidText = target.Text;
}
}
private static bool ContainsNumber(string input)
{
return Regex.IsMatch(input, #"\d+");
}
This will handle any occurrence of numbers in the text, regardless of where or how many times they may appear.
use the TextBox.TextChanged event. Then use the same code as you have in the KeyDown event. In fact, you no longer need the keydown event
You can use the JavaScript change event (onchange) instead of the keydown event. It'll check only when the user leaves the textbox though.