0

Made a button to add "links" to "richTextBox". "Links" are added not to the text, but from above "richTextBox".

Question
How to make the "links" added to the text based on the current code or based on another solution?

 LinkLabel link = new LinkLabel();
        link.Text = "*** LINK ***";

        // link.LinkClicked
        link.LinkClicked += new LinkLabelLinkClickedEventHandler(this.link_LinkClicked);

        // data
        LinkLabel.Link data = new LinkLabel.Link();
        data.LinkData = @"C:\";

        // link
        link.Links.Add(data);
        link.AutoSize = true;
        link.Location =
            this.richTextBox1.GetPositionFromCharIndex(this.richTextBox1.TextLength);

        // richTextBox1
        this.richTextBox1.Controls.Add(link);
        this.richTextBox1.AppendText(link.Text + "   ");
        this.richTextBox1.SelectionStart = this.richTextBox1.TextLength;

GIF

climivin
  • 301
  • 1
  • 9
  • Reading [this](https://learn.microsoft.com/en-us/dotnet/framework/winforms/controls/how-to-display-web-style-links-with-the-windows-forms-richtextbox-control) might help – Shanid May 10 '18 at 11:10

2 Answers2

1

This is wronga approach. The text in RichTextBox is not parts of Controls, so if you add LinkLabel into Controls, their positions will not be synchronized.

Look at this question How can I make a hyperlink work in a RichTextBox?

TcKs
  • 25,849
  • 11
  • 66
  • 104
  • Thank you. I read it. If I understand correctly, this solution is used if in the "RichTextBox" only the link. I use the following text structure in "RichTextBox": "Line 1-Text, Line 2-Reference, Line 3-Text, Line 4-Reference" I'm sorry if I did not understand something. I'm an inexperienced programmer. – climivin May 10 '18 at 11:28
  • 1
    This approach will break in several cases. For example if you will show scroll the content. Or the system font (size) will be different. Or if one line will be wraped to next line, etc... – TcKs May 10 '18 at 11:31
1

As an alternative to the solution by TcKs, check this: Links with arbitrary text in a RichTextBox

An author of related article wrote:

every time the text in the RichTextBox is changed, the text is parsed for URLs and the matching text ranges are formatted as links (underlined, blue foreground by default)

Maciej Los
  • 8,468
  • 1
  • 20
  • 35