Reputation: 684
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?
Upvotes: 0
Views: 3469
Reputation: 66439
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));
}
Upvotes: 1
Reputation: 2168
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.
Upvotes: 2
Reputation: 32681
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
Upvotes: 3