在C#中的RichTexbox中选择文本会删除文本
我在从 Richtextbox 派生的控件中输入了以下文本
“The world is {beautful}”。
我的主要目的是为“美丽”这个词创建一个链接。 我可以使用 CFE_LINK 创建它,但那是我选择文本的时候。
当我使用 Select (4,9) 时,4 到 9 范围内的文本将被删除。
有人可以帮我解决我遗漏的内容吗?
代码:
我正在创建一个源自 Richtextbox 的用户控件。
我在下面给出了确切的代码; 我没有做任何颜色改变。 我认为“选择”命令默认将所选文本设置为蓝色。
protected override void OnKeyPress(KeyPressEventArgs e)
{
String keypressed = e.KeyChar.ToString();
if(keypressed == "}")
Select(4,9)
base.OnKeyPress(e);
}
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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
起初,当我开始搞乱这个时,我也很困惑。 但后来我突然想到,你按下的键很可能被发送到文本框以在 KeyUp 处呈现。 果然,当我将你的代码更改为这样时,它起作用了:
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:
我怀疑当按下“}”键时,您的代码会在字符发送到文本框之前运行。
因此,您选择文本,然后“}”字符被发送到文本框,覆盖选择内容。
编辑:是的,转载了。
我不知道如何解决它。 也许实现
OnTextChanged
会更好。您可以扫描整个文本框以查找未链接的{大括号内的单词}。 如果文本很大,它可能会更慢,但它会自动处理复制和粘贴之类的事情。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.我投票支持 BFree 的答案,但如果由于某种原因你必须使用 OnKeyPress 方法,你可以调用 select 方法,所以它会在事件完成后发生。
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.
根据 Blorgbeard 的回答,您首先选择文本,然后在文本框中键入“
}
”,替换您的选择。 也许您想要的是先输入“}
”,然后然后进行选择。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.