如何处理或删除LinkLabel的尾随空格?

时间:2017-07-21 16:01:15

标签: c# winforms linklabel

我正在尝试将链接插入我的RichTextBox。我不是说将DetectUrls设置为true,我想要替换文本。到目前为止我所做的工作似乎很好......我正在使用this solution中的大部分代码。但我的问题是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());
}

以下是我看到的内容,供参考(请注意缺少的'&lt;'):

enter image description here

使用RichTextBox的原因是我还计划在完成时添加格式(文本为粗体,彩色等的能力)。我基本上距离废弃RichTextBox并手动将所有内容绘制到面板并处理点击位置2小时......

0 个答案:

没有答案