突出显示格式文本框中的一行文本

本文关键字:文本 一行 显示格式 | 更新日期: 2023-09-27 18:32:36

所以我正在开发一个程序,为用户提供数据结构和排序算法的3D可视化。 我想做的是在 UI 上有一个富文本框,显示正在执行的特定算法的代码。 然后,我希望在执行代码时突出显示代码的每一行。 我只是想从可视化堆栈开始,因为在我学习和完成这个项目时,它更容易处理。 现在我有一个 c++ 推送和弹出函数的文本文件,我正在将文本保存到列表中。 然后,我将文本写入富文本框。 所有这些都有效,但我不知道如何突出显示一行,然后突出显示下一行。 例如,当我单击"push"时,我希望它突出显示"list[stackTop] = newItem;",然后绘制3d立方体(已经完成(,然后突出显示"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++;
        }
    }

这些不是他们教我大学的话题。 我只是在这里自学。 因此,如果我完全错误地对待这个问题,我对这里的任何事情都持开放态度。

这是我的"stackPush"按钮的事件处理程序。

    //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++;
    }

突出显示格式文本框中的一行文本

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

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