Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
644 views
in Technique[技术] by (71.8m points)

c# - Broken hyperlinks in RTF file in RichTextBox

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).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...