突出显示richtextbox中的一行文本

时间:2014-11-30 20:28:51

标签: c# winforms richtextbox

所以我正在开发一个程序,为用户提供数据结构和排序算法的三维可视化。我想要做的是在UI上有一个richtextbox,显示正在执行的特定算法的代码。然后我想让代码的每个特定行在执行时突出显示。我只想从可视化堆栈开始,因为在我学习和完成这个项目时,它更容易处理。现在我有一个c ++推送和弹出功能的文本文件,我将文本保存到列表中。然后我将文本写入richtextbox。所有这一切都有效,但我不知道如何突出显示一行,然后突出显示下一行。例如,当我点击"推"我希望它突出显示" list [stackTop] = newItem;"然后绘制三维立方体(已经完成),然后突出显示" stackTop ++"线。然后用户可以再次或他们想要的任何其他内容。

class CppFunctionsArray
    {
    List<string> ReadFunctions = new List<string>();
    int Position = 0;

    //Reads input from selected file and stores into ReadFunctions Array;
    public void ReadInput(string fileName)
    {

        using (StreamReader r = new StreamReader(fileName))
        {
            string line;
            while ((line = r.ReadLine()) != null)
            {
                ReadFunctions.Add(line);
            }
        }
    }

    //Writes lines to a RichTextBox.
    public void WriteToRichTextBox(RichTextBox rtb, int startIndex, int endIndex, int  lineNumber)
    {
        Position = 0;
        for (int i = startIndex; i < endIndex; i++)
        {
            rtb.AppendText(ReadFunctions[i]);
            rtb.AppendText(Environment.NewLine);
            rtb.Font = new Font("times new roman", 12, FontStyle.Bold);

            //Temporary
            if (lineNumber == Position)
                  rtb.SelectionBackColor = Color.Red;
            Position++;

        }
    }

这些不是他们教我上大学的主题。我只是在这里教自己。因此,如果我接近这个完全错误的话,我愿意接受任何事情。

这是&#34; stackPush&#34;的事件处理程序。按钮。

    //Adds cube on top of the previous.
    private void StackPush_Click(object sender, EventArgs e) 
    {

        CppFunctionsArray ArrayOfFunctions = new CppFunctionsArray();
        CodeTextBox.Clear();
        ArrayOfFunctions.ReadInput("StackFunctions.txt");

        //The 4 represents the line Number to highlight. TODO FIX THIS.
        ArrayOfFunctions.WriteToRichTextBox(CodeTextBox, 1, 12,4);

        //Draws a new cube of 1 unit length.
        cube = new Visual();
        //Adds cube to list;
        cubeList.Add(cube);
        cube.y = position;
        position++;

    }

1 个答案:

答案 0 :(得分:2)

如果您正在寻找一种扩展方法来清除RichTextBox所有行的背景颜色,然后为特定行着色,则以下内容就足够了:

    public static void HighlightLine(this RichTextBox richTextBox, int index, Color color)
    {
        richTextBox.SelectAll();
        richTextBox.SelectionBackColor = richTextBox.BackColor;
        var lines = richTextBox.Lines;
        if (index < 0 || index >= lines.Length)
            return;
        var start = richTextBox.GetFirstCharIndexFromLine(index);  // Get the 1st char index of the appended text
        var length = lines[index].Length;
        richTextBox.Select(start, length);                 // Select from there to the end
        richTextBox.SelectionBackColor = color;
    }