C# – Broken hyperlinks in RTF file in RichTextBox

cnetrichtextboxrtfwinforms

I'm using a RichTextBox to display an RTF file, which includes a single hyperlink. The link text is not a URL (the target is a valid URL). The RTF was created with Word. Both Word and WordPad properly recognize the links (WordPad does not launch the links, but shows the appropriate hand cursor).

When I load the RTF into a RichTextBox the links appear formatted correctly (blue and underlined), but rather than behaving like a link, when the cursor moves over the link it remains an I-beam, the LinkClicked event will not fire, and it actually shows the target between angle brackets after the link (this does not seem correct). Since the link text is not a URL, DetectUrls does not help here.

Is there a reason that RichTextBox does not properly handle these links, or a way to make them work as expected?

Here is the code.

TipView.Rtf = tips[tipIndex];
// I've also tried TipView.LoadFile, with identical result

To reproduce the issue, create an RTF document with Word (I'm using 2000) containing one link whose text is not a URL but targets a valid URL, and programatically load the .rtf file into a RichTextBox (I'm using .NET 2.0 in C# Express 2008).

Best Answer

To support hyperlinks, you need RICHEDIT50W version of "rich edit".

For that:

  • Either use .NET Framework 4.7, which uses RICHEDIT50W natively in RichTextBox.
  • In older versions of .NET Framework, you can modify RichTextBox to use RICHEDIT50W:

    public class ExRichText : RichTextBox
    {
        [DllImport("kernel32.dll", EntryPoint = "LoadLibraryW",
                   CharSet = CharSet.Unicode, SetLastError = true)]
        private static extern IntPtr LoadLibraryW(string s_File);
    
        protected override CreateParams CreateParams
        {
            get
            {
                var cp = base.CreateParams;
                LoadLibraryW("MsftEdit.dll");
                cp.ClassName = "RichEdit50W";
                return cp;
            }
        }
    }
    

Based on RichTextBox Selection Highlight and RichTextBox cannot display Unicode Mathematical alphanumeric symbols.

Related Topic