【问题标题】:Highlight Entire Line in RichTextBox C#在 RichTextBox C# 中突出显示整行
【发布时间】:2017-11-23 02:48:37
【问题描述】:

我的 C# winforms 应用程序中有一个 Richtextbox,但无法找到突出显示整行(文本部分 + 任何空格)的方法。我只能使用以下代码突出显示该行上的文本:

firstCharIndex = richTextBox.Text.IndexOf(header);
headerLine = richTextBox.GetLineFromCharIndex(firstCharIndex);
headerLineText = richTextBox.Lines[headerLine];

int lastCharIndex = richTextBox.GetFirstCharIndexFromLine(headerLine + 1);

//richTextBox.Select(firstCharIndex, headerLineText.Length);
richTextBox.Select(firstCharIndex, lastCharIndex - firstCharIndex);

if (richTextBox.SelectionBackColor != System.Drawing.Color.DarkGray)
{
    richTextBox.SelectionBackColor = System.Drawing.Color.DarkGray;
}

【问题讨论】:

    标签: c# winforms richtextbox


    【解决方案1】:

    使用“select”的第二个重载来减少计算量。

    查看 cmets。

            //Rich text box
            richTextBox1.Text = "test test1 test test                              ";
    
            //Get the first index in the line from where you want to select.
            int firstCharIndex = richTextBox1.Text.IndexOf("test1");
    
            //Get the line based on character index.
            int line = richTextBox1.GetLineFromCharIndex(firstCharIndex);
    
            //Get the line it self.
            string headerLineText = richTextBox1.Lines[line];
    
            //Use second ovrload of select method and pass length of the line as second parameter
            //with the below approach, you can start highlighting from any where in the line.
            richTextBox1.Select(firstCharIndex, headerLineText.Length- firstCharIndex);
    

    【讨论】:

    • 我已经试过了。它仅突出显示包含文本的行的一部分。此外,我的表单(以及文本框)是可调整大小的。因此,如果我增加宽度,该行仍应保持突出显示。
    • 如果您的代码没有有效的下一行,则 lastCharIndex 值将为-1。所以我不建议使用它。完全按照我在代码中所说的尝试
    • 我注意到你用空白空间填充了文本。这是我以前做过的,但问题是你不知道表格有多宽。没有在文本末尾手动添加空格就没有办法突出显示整行?
    • 你的意思是文本后面的空格??。该空间不是文本的一部分......所以你不会有任何指标。
    • 我将您的代码复制到我的程序中,它只突出显示了 .Text 属性中包含的字符串。但我想突出显示文本框中的整行/行,所以即使我增加表单(文本框)的宽度,整行仍然突出显示。我希望我很清楚。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-05
    • 2011-08-26
    • 2015-05-10
    • 2013-11-13
    • 1970-01-01
    • 2012-07-23
    • 2016-03-19
    相关资源
    最近更新 更多