Selecting text in RichTexbox in C# deletes the text

末鹿安然 提交于 2019-12-24 06:25:55

问题


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

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

    }



回答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.




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



回答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)        
}


来源:https://stackoverflow.com/questions/892370/selecting-text-in-richtexbox-in-c-sharp-deletes-the-text

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!