Calculate length of text entered in RichTextBox c# winform - c#

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

Related

Replace pressed key in TextBox to another C#

How can I replace pressed 'decimal point' key from numpad to always return '.' independent of regional setting. I want that works only for one (specific) TextBox not all in application.
It's possible to accomplished this without creating own control?
This is a possible solution (most possibly not the best one, but one that should work) that would add a . character to a textbox if the decimal key on the numpad is pressed, if the , key is pressed it still adds the , character to the textbox.
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Decimal)
{
e.SuppressKeyPress = true;
textBox1.Text += ".";
textBox1.SelectionStart = textBox1.Text.Length;
textBox1.SelectionLength = 0;
}
}
The SuppressKeyPress prevents that the pressed key is sent to the textbox. Then you add the desired character to the textbox. The SelectionStart and SelectionLength properties are set to move the cursor to the end of the string in the textbox.
Hope that helps
EDIT:
As cdkMoose pointed out the flaw with this approach is that the .character is always added to the end of the string, if it is desired to add the .character anywhere in the string the code could be used like this:
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Decimal)
{
e.SuppressKeyPress = true;
var caretPosition = textBox1.SelectionStart;
textBox1.Text.Insert(caretPosition , ".");
textBox1.SelectionStart = caretPosition + 1;
textBox1.SelectionLength = 0;
}
}
In order to do this, you simply need to handle the KeyDown event, supress the activated key if its the numpad decimal, and then simply send the new key you want.
It's pretty straightforward, the following links should give you enough pointers to actually write some code:
Keys
Control.KeyDown
KeyEventArgs
SendKeys
Once you've written something, you can ask a new question about any specific dificulties you might encounter.
Look at this.
You can handle KeyDown event and if is , on numpad cancel event and send new with '.'.

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.
}
}

Get changed text from rich textbox

So, I am looking for the best way to get the text that has changed either using the keyPressed event, put preferably the TextChanged event. What I'm looking for is what has been changed. I have a program that should send events to another window and populate the rich textbox there with a color. I tried the following using the keyPressed event:
private void richTextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
char keyChar = (char) e.KeyChar;
if (Char.IsLetterOrDigit(keyChar) || Char.IsSeparator(keyChar)
|| Char.IsWhiteSpace(keyChar))
{
string changedText = keyChar.ToString();
VinduEventArgs ve = new VinduEventArgs(colorDialog1.Color, changedText);
VinduEndret(this, ve);
}
}
But it doesn't really work as it's buggy, doesn't show all signs, and seems kindof like a bad solution.

Winform RichTextBox get last character entered using c#

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

Prevent numbers from being pasted in textbox in .net windows forms

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.

Categories

Resources