简体   繁体   中英

How to show number of a line in a RichTextBox C#

I am making a simple text and script editor with code highlighting. For that I use a RichTextBox. But I don't know how to make it show the lines' numbers on the left side, like in VS or Notepad++. Is there any solution?

I tried re-using the code from the codeproject articles referenced elsewhere, but every option I looked at, seemed a bit too kludgy.

So I built another RichTextBoxEx that displays line numbers.

The line numbering can be turned on or off. It's fast. It scrolls cleanly. You can select the color of the numbers, the background colors for a gradient, the border thickness, the font, whether to use leading zeros. You can choose to number lines "as displayed" or according to the hard newlines in the RTB.

Examples:

在此输入图像描述

在此输入图像描述

在此输入图像描述

It has limitations: it displays numbers only on the left. You could change that without too much effort if you cared.

The code is designed as C# project. Though it's part of a larger "solution" (an XPath Visualization tool), the custom RichTextBox is packaged as a separable assembly, and is ready to use in your new projects. In Visual Studio, just add a reference to the DLL, and you can drag-and-drop it onto your design surface. You can just discard the other code from the larger solution.

See the code

I would store each line in a class which has methods to publish to the richtextbox. In that method, you could prepend the line number based on its position in the class.

For example (very roughly):

class myText
{
    public List<string> Lines;

    public string GetList()
    {
        StringBuilder sb = new StringBuilder();
        int i = 0;
        foreach (string s in Lines)
        {
            sb.AppendFormat("{0}: {1}", i, s).AppendLine();
            i++;
        }
        return sb.ToString();
    }
}
    public int getWidth()
    {
        int w = 25;
        // get total lines of richTextBox1
        int line = richTextBox1.Lines.Length;

        if (line <= 99)
        {
            w = 20 + (int)richTextBox1.Font.Size;
        }
        else if (line <= 999)
        {
            w = 30 + (int)richTextBox1.Font.Size;
        }
        else
        {
            w = 50 + (int)richTextBox1.Font.Size;
        }

        return w;
    }

    public void AddLineNumbers()
    {
        // create & set Point pt to (0,0)
        Point pt = new Point(0, 0);
        // get First Index & First Line from richTextBox1
        int First_Index = richTextBox1.GetCharIndexFromPosition(pt);
        int First_Line = richTextBox1.GetLineFromCharIndex(First_Index);
        // set X & Y coordinates of Point pt to ClientRectangle Width & Height respectively
        pt.X = ClientRectangle.Width;
        pt.Y = ClientRectangle.Height;
        // get Last Index & Last Line from richTextBox1
        int Last_Index = richTextBox1.GetCharIndexFromPosition(pt);
        int Last_Line = richTextBox1.GetLineFromCharIndex(Last_Index);
        // set Center alignment to LineNumberTextBox
        LineNumberTextBox.SelectionAlignment = HorizontalAlignment.Center;
        // set LineNumberTextBox text to null & width to getWidth() function value
        LineNumberTextBox.Text = "";
        LineNumberTextBox.Width = getWidth();
        // now add each line number to LineNumberTextBox upto last line
        for (int i = First_Line; i <= Last_Line + 2; i++)
        {
            LineNumberTextBox.Text += i + 1 + "\n";
        }
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        LineNumberTextBox.Font = richTextBox1.Font;
        richTextBox1.Select();
        AddLineNumbers();
    }

    private void richTextBox1_SelectionChanged(object sender, EventArgs e)
    {
        Point pt = richTextBox1.GetPositionFromCharIndex(richTextBox1.SelectionStart);
        if (pt.X == 1)
        {
            AddLineNumbers();
        }
    }

    private void richTextBox1_VScroll(object sender, EventArgs e)
    {
        LineNumberTextBox.Text = "";
        AddLineNumbers();
        LineNumberTextBox.Invalidate();
    }

    private void richTextBox1_TextChanged(object sender, EventArgs e)
    {
        if (richTextBox1.Text == "")
        {
            AddLineNumbers();
        }
    }

    private void richTextBox1_FontChanged(object sender, EventArgs e)
    {
        LineNumberTextBox.Font = richTextBox1.Font;
        richTextBox1.Select();
        AddLineNumbers();
    }

    private void LineNumberTextBox_MouseDown(object sender, MouseEventArgs e)
    {
        richTextBox1.Select();
        LineNumberTextBox.DeselectAll();
    }

    private void Form1_Resize(object sender, EventArgs e)
    {
        AddLineNumbers();
    }

Scintilla.Net http://scintillanet.codeplex.com/ could be the most feasible solution for your needs. But for my project I used solution suggested by Cheeso (RichTextBoxEx from XPath visualizer). It's simple and fast enough for not very big documents. All other .net components from the internet were incredibly slow.

The simple way:

Dim myArray = RichTextBox1.Text.Split()

Dim cnt As Integer = 0
RichTextBox1.Clear()

Do While cnt < myArray.Count
  RichTextBox1.AppendText(cnt & ":" & myArray(cnt) & vbNewLine)
  cnt = cnt + 1
Loop

You can achieve that by drawing your own control. Here's an example how to draw yourself link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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