Tutorial :Selecting text in RichTexbox in C# deletes the text



Question:

I have typed in the following text in a control derived from Richtextbox

"The world is {beautful}".

My main intention is to create a link for the word beautful. I can create this using CFE_LINK , but that's when I select the text.

When I use Select (4,9), the text within the range 4 to 9 gets deleted.

Can someone please help me with what I am missing out?

CODE :

I am creating a User Control, derived from Richtextbox.

I am giving the exact code below; I have not done any color change. I think the Select command sets the selected text to blue by default.

protected override void OnKeyPress(KeyPressEventArgs e)  {     String keypressed =  e.KeyChar.ToString();     if(keypressed == "}")        Select(4,9)             base.OnKeyPress(e);  }  


Solution:1

At first when I started messing with this, I was puzzled as well. But then it hit me, it's very possible that your key that's being pressed is being sent to the textbox to render at KeyUp. Sure enough, when I changed your code to this it worked:

    protected override void OnKeyUp(KeyEventArgs e)      {          base.OnKeyUp(e);          if (e.KeyCode == Keys.Oem6)          {             Select(4, 9);          }        }  


Solution:2

I suspect that when the '}' key is pressed, your code runs before the character is sent to the textbox.

So you select the text, and then the '}' character is sent to the textbox, overwriting the selection.

Edit: Yup, reproduced it.

I'm not sure off the top of my head how to solve it. Perhaps it would be better to implement OnTextChanged instead.. You could scan the entire textbox for unlinked {words inside braces}. It might be slower if the text is large, but it would automatically handle copy and paste and things like that.


Solution:3

I voted for BFree's answer, but if for some reason you must use OnKeyPress method, you can invoke the select method, so it happens after the event has completed.

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


Solution:4

According to Blorgbeard's answer, you are selecting the text first, and then the "}" is typed into the textbox, replacing your selection. Maybe what you want is to type the "}" first and then make the selection.

protected override void OnKeyPress(KeyPressEventArgs e)  {     // type "}" into textbox     base.OnKeyPress(e);       String keypressed =  e.KeyChar.ToString();       if(keypressed == "}")        Select(4,9)          }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »