简体   繁体   English

使用C#突出显示TextBox / Label / RichTextBox中的文本

[英]Highlight text in TextBox/Label/RichTextBox using C#

Good night, 晚安,

I would like to know how can I highlight a part of the text contained in a TextBox, Label (preferably) or RichTextBox. 我想知道如何突出显示TextBox,Label(最好)或RichTextBox中包含的文本的一部分。 For example, given the string 例如,给定字符串

"This is a test.", “这是一个测试。”,

I would like the control to show "This is a test .". 我希望控件显示“这是一个测试 。”。 Is there any easy way I can do it? 有什么简单的方法可以做到吗?

Thank you very much. 非常感谢你。

RichTextBox r = new RichTextBox();
r.Text = "This is a test";
r.Select(r.Text.IndexOf("test"), "test".Length);
r.SelectionFont = new Font(r.Font, FontStyle.Italic);
r.SelectionStart = r.Text.Length;
r.SelectionLength = 0;

Something to that effect will work and remove the selection. 这样的效果将起作用并删除选择。

EDIT It should be relatively easy to encapsulate in your own method. 编辑在您自己的方法中封装应该相对容易。 You could even make an extension: 你甚至可以进行扩展:

public static class Extensions
{
    public static void StyleText(this RichTextBox me, string text, FontStyle style)
    {
        int curPos = me.SelectionStart;
        int selectLen = me.SelectionLength;
        int len = text.Length;
        int i = me.Text.IndexOf(text);

        while (i >= 0)
        {
            me.Select(i, len);
            me.SelectionFont = new Font(me.SelectionFont, style);
            i = me.Text.IndexOf(text, i + len);
        }

        me.SelectionStart = curPos;
        me.SelectionLength = selectLen;
    }
}

and then use it like: 然后使用它像:

richTextBox1.Text = "This is a test";
richTextBox1.StyleText("test", FontStyle.Italic);

Using a RichTextBox it would be approximately: 使用RichTextBox大约是:

textbox.Text = "This is a test.";
textbox.Select(10, 4);
textbox.SelectionFont = new Font(textBox.SelectionFont, FontStyle.Italic);

This isn't possible on a single label, though you could use two. 这在单个标签上是不可能的,但您可以使用两个。

I'm not completely sure Style is writeable now that I think about it. 我现在并不完全确定Style是可写的,我想一想。

Edit: Fixed. 编辑:已修复。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM