Selecting text in RichTexbox in C # deletes text
I typed the following text in a control from Richtextbox
"The world is {beautful}".
My main goal is to create a link for the word beautful. I can create this with CFE_LINK, but this is when I select text.
When I use Select (4.9), the text in the range 4 to 9 is removed.
Can someone please help me with what I am missing?
THE CODE:
I am creating User Control derived from Richtextbox.
I am giving the exact code below; I didn't make any color changes. I think the Select command sets the selected blue text by default.
protected override void OnKeyPress(KeyPressEventArgs e)
{
String keypressed = e.KeyChar.ToString();
if(keypressed == "}")
Select(4,9)
base.OnKeyPress(e);
}
a source to share
At first when I started tinkering with this, I was puzzled too. But then it hit me, it is very possible that your key that is pressed is being sent to the textbox for rendering in KeyUp. Of course, when I changed the code to this, it worked:
protected override void OnKeyUp(KeyEventArgs e)
{
base.OnKeyUp(e);
if (e.KeyCode == Keys.Oem6)
{
Select(4, 9);
}
}
a source to share
I suspect that when you press the "}" key, your code runs before the character is sent to the textbox.
So you select the text and then the "}" character is sent to the text field, overwriting the selection.
Edit: Yup, reproduced it.
I'm not sure how to solve this. It might be better to implement OnTextChanged
this instead. You could scan the entire text box for unbound {words inside curly braces}. It can be slower if the text is large, but it automatically handles copy and paste and the like.
a source to share
I upvoted BFree's answer, but if for some reason you must use the OnKeyPress method, you can call the select method, so this happens after the event ends.
protected delegate void SelectAfterKeyPress(int start, int length);
protected override void OnKeyPress(KeyPressEventArgs e)
{
base.OnKeyPress(e);
String keypressed = e.KeyChar.ToString();
if (keypressed == "}")
{
this.BeginInvoke(new SelectAfterKeyPress(Select), new object[] { 4, 9 });
}
}
a source to share
As per Blorgbeard's answer , you first select the text and then " }
" is entered into the textbox, replacing your selection. Perhaps you want to enter " }
" first and then make a selection.
protected override void OnKeyPress(KeyPressEventArgs e)
{
// type "}" into textbox
base.OnKeyPress(e);
String keypressed = e.KeyChar.ToString();
if(keypressed == "}")
Select(4,9)
}
a source to share