0

我正在尝试将链接插入到我的RichTextBox. 我并不是说将 DetectUrls 设置为 true,我想要替代文本。到目前为止,我的工作似乎大部分都很好。我正在使用这个解决方案中的大部分代码。但我的问题是,结尾处有一些尾随空格会LinkLabel切断它后面的一些文本。

这是我到目前为止所拥有的:

private void Form1_Load(object sender, EventArgs e)
{
    //My text with a placeholder for the link: %link1%
    //NOTE: I can see the leading '>' fine, but the '<' gets hidden by the link label, and it looks like a space between the link text and "Near..."
    richTextBox1.Text = "This has a link here:>%link1%<Near the middle.";

    LinkLabel link1 = new LinkLabel();
    //link1.Margin = new Padding(0); //Doesn't help
    //link1.Padding = new Padding(0); //Default is already 0
    //What I want to see in my hyperlink
    link1.Text = "My_Link_Text";
    link1.Font = richTextBox1.Font;
    link1.LinkColor = Color.DodgerBlue;
    link1.LinkClicked += Link_LinkClicked;
    LinkLabel.Link data = new LinkLabel.Link();
    //For now, just test with google.com...
    data.LinkData = @"http://google.com";
    link1.Links.Add(data);
    link1.AutoSize = true;
    link1.Location = this.richTextBox1.GetPositionFromCharIndex(richTextBox1.Text.IndexOf("%link1%"));
    richTextBox1.Controls.Add(link1);
    //Replace the placeholder with the text I want to see so that the link gets placed over this text
    richTextBox1.Text = richTextBox1.Text.Replace("%link1%", link1.Text);

    //Attempt to manually shrink the link by a few pixels (doesn't work)
    //NOTE: Turns out this cuts back on the link test, but leave the trailing space :(
    //Size s = new Size(link1.Width, link1.Height); //Remember the autosized size (it did the "hard" work)
    //link1.AutoSize = false; //Turn off autosize
    //link1.Width = s.Width - 5;
    //link1.Height = s.Height;
}

LinkClicked 事件,只是为了好奇。没什么特别的。

private void Link_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
    System.Diagnostics.Process.Start(e.Link.LinkData.ToString());
}

这是我看到的,供参考(注意缺少的'<'):

在此处输入图像描述

使用 a 的原因RichTextBox是我还计划在完成后添加格式(文本加粗、彩色等的能力)。我基本上需要 2 个小时才能将RichTextBox所有内容手动绘制到面板上并处理点击位置......

4

0 回答 0