C# 富文本框中的链接?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9855292/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 10:56:09  来源:igfitidea点击:

Links inside rich textbox?

c#winformshyperlinkrichtextboxrtf

提问by Oztaco - Reinstate Monica C.

I know that richtextboxes can detect links (like http://www.yahoo.com) but is there a way for me to add links to it that looks like text but its a link? Like where you can choose the label of the link? For example instead of it appearing as http://www.yahoo.comit appears as Click here to go to yahoo

我知道 Richtextboxes 可以检测链接(如http://www.yahoo.com),但是有没有办法让我向它添加看起来像文本但它是链接的链接?比如在哪里可以选择链接的标签?例如,它不是显示为http://www.yahoo.com,而是显示为Click here to go to yahoo

edit: forgot, im using windows forms

编辑:忘记了,我正在使用 Windows 窗体

edit: is there something thats better to use (as in easier to format)?

编辑:有没有更好的东西(比如更容易格式化)?

采纳答案by Mario Frai?

Of course it is possible by invoking some WIN32 functionality into your control, but if you are looking for some standard ways, check this post out: Create hyperlink in TextBox control

当然可以通过在您的控件中调用一些 WIN32 功能,但是如果您正在寻找一些标准方法,请查看这篇文章: 在 TextBox 控件中创建超链接

There are some discussions about different ways of integration.

有一些关于不同集成方式的讨论。

greetings

你好

Update 1: The best thing is to follow this method: http://msdn.microsoft.com/en-us/library/f591a55w.aspx

更新 1:最好的方法是遵循此方法:http: //msdn.microsoft.com/en-us/library/f591a55w.aspx

because the RichText box controls provides some functionality to "DetectUrls". Then you can handle the clicked links very easy:

因为 RichText 框控件为“DetectUrls”提供了一些功能。然后你可以很容易地处理点击的链接:

this.richTextBox1.LinkClicked += new System.Windows.Forms.LinkClickedEventHandler(this.richTextBox1_LinkClicked);

and you can simple create your own RichTextBox contorl by extending the base class - there you can override the methods you need, for example the DetectUrls.

并且您可以通过扩展基类来简单地创建您自己的 RichTextBox 控件 - 在那里您可以覆盖您需要的方法,例如 DetectUrls。

回答by Alan

The standard RichTextBox control (assuming you are using Windows Forms) exposes a rather limited set of features, so unfortunately you will need to do some Win32 interop to achieve that (along the lines of SendMessage(), CFM_LINK, EM_SETCHARFORMAT etc.).

标准 RichTextBox 控件(假设您使用的是 Windows 窗体)公开了一组相当有限的功能,因此不幸的是,您需要执行一些 Win32 互操作来实现这一点(沿着 SendMessage()、CFM_LINK、EM_SETCHARFORMAT 等)。

You can find more information on how to do that in this answerhere on SO.

您可以在 SO 上的此答案中找到有关如何执行操作的更多信息。

回答by Nima Soroush

Here you can find an example of adding a link in rich Textbox by linkLabel:

在这里你可以找到一个通过linkLabel在富文本框中添加链接的例子:

    LinkLabel link = new LinkLabel();
    link.Text = "something";
    link.LinkClicked += new LinkLabelLinkClickedEventHandler(this.link_LinkClicked);
    LinkLabel.Link data = new LinkLabel.Link();
    data.LinkData = @"C:\";
    link.Links.Add(data);
    link.AutoSize = true;
    link.Location =
        this.richTextBox1.GetPositionFromCharIndex(this.richTextBox1.TextLength);
    this.richTextBox1.Controls.Add(link);
    this.richTextBox1.AppendText(link.Text + "   ");
    this.richTextBox1.SelectionStart = this.richTextBox1.TextLength;

And here is the handler:

这是处理程序:

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

回答by Guido Domenici

I found a way which may not be the most elegant, but it's just a few lines of code and does the job. Namely, the idea is to simulate hyperlink appearance by means of font changes, and simulate hyperlink behavior by detecting what the mouse pointer is on.

我找到了一种可能不是最优雅的方法,但它只需要几行代码就可以完成工作。也就是说,这个想法是通过改变字体来模拟超链接的外观,并通过检测鼠标指针所在的位置来模拟超链接的行为。

The code:

编码:

public partial class Form1 : Form
{
    private Cursor defaultRichTextBoxCursor = Cursors.Default;
    private const string HOT_TEXT = "click here";
    private bool mouseOnHotText = false;

    // ... Lines skipped (constructor, etc.)

    private void Form1_Load(object sender, EventArgs e)
    {
        // save the right cursor for later
        this.defaultRichTextBoxCursor = richTextBox1.Cursor;

        // Output some sample text, some of which contains
        // the trigger string (HOT_TEXT)
        richTextBox1.SelectionFont = new Font("Calibri", 11, FontStyle.Underline);
        richTextBox1.SelectionColor = Color.Blue;
        // output "click here" with blue underlined font
        richTextBox1.SelectedText = HOT_TEXT + "\n";

        richTextBox1.SelectionFont = new Font("Calibri", 11, FontStyle.Regular);
        richTextBox1.SelectionColor = Color.Black;
        richTextBox1.SelectedText = "Some regular text";
    }

    private void richTextBox1_MouseMove(object sender, MouseEventArgs e)
    {
        int mousePointerCharIndex = richTextBox1.GetCharIndexFromPosition(e.Location);
        int mousePointerLine = richTextBox1.GetLineFromCharIndex(mousePointerCharIndex);
        int firstCharIndexInMousePointerLine = richTextBox1.GetFirstCharIndexFromLine(mousePointerLine);
        int firstCharIndexInNextLine = richTextBox1.GetFirstCharIndexFromLine(mousePointerLine + 1);
        if (firstCharIndexInNextLine < 0)
        {
            firstCharIndexInNextLine = richTextBox1.Text.Length;
        }

        // See where the hyperlink starts, as long as it's on the same line
        // over which the mouse is
        int hotTextStartIndex = richTextBox1.Find(
            HOT_TEXT, firstCharIndexInMousePointerLine, firstCharIndexInNextLine, RichTextBoxFinds.NoHighlight);

        if (hotTextStartIndex >= 0 && 
            mousePointerCharIndex >= hotTextStartIndex && mousePointerCharIndex < hotTextStartIndex + HOT_TEXT.Length)
        {
            // Simulate hyperlink behavior
            richTextBox1.Cursor = Cursors.Hand;
            mouseOnHotText = true;
        }
        else
        {
            richTextBox1.Cursor = defaultRichTextBoxCursor;
            mouseOnHotText = false;
        }
        toolStripStatusLabel1.Text = mousePointerCharIndex.ToString();
    }

    private void richTextBox1_MouseClick(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left && mouseOnHotText)
        {
            // Insert your own URL here, to navigate to when "hot text" is clicked
            Process.Start("http://www.google.com");
        }
    }
}

To improve on the code, one could create an elegant way to map multiple "hot text" strings to their own linked URLs (a Dictionary<K, V>maybe). An additional improvement would be to subclass RichTextBoxto encapsulate the functionality that's in the code above.

为了改进代码,可以创建一种优雅的方式将多个“热文本”字符串映射到它们自己的链接 URL(Dictionary<K, V>可能)。另一个改进是子类化RichTextBox以封装上面代码中的功能。