0

I have a rich textbox and I want to use a hyperlink on it, so when the user clicks it, the website link or local file is opened. In my last question, I said that link click event does not fire properly, this problem is solved, but now I have another problem.

I try to create a hyperlink and my characters are in utf8 (Farsi/arabic). But for example when I write this text

سلام چطوری خوبم خوبی؟ چه خبر؟

and choose "چه" as link text and "C:\Users\sadegh\Desktop\16.txt" as url, the result is:

سلام چطوری خوبم خوبی؟ ?? file://C:/Users/sadegh/Desktop/16.txtخبر؟

How can I fix this? My code is:

private void AddLinkBtn_Click(object sender, EventArgs e)
{
    string url = null;
    
    OpenFileDialog openFileDialog = new OpenFileDialog();
    //openFileDialog.Filter = "Image Files (*.jpg;*.jpeg,*.png)|*.JPG;*.JPEG;*.PNG";
    openFileDialog.Multiselect = false;
    
    if (openFileDialog.ShowDialog() == DialogResult.OK)
    {
        url = openFileDialog.FileName;
    }
    
    if (!string.IsNullOrEmpty(url))
    {
        string linkText = TextBoxDefinition.SelectedText;
        byte[] bytes = Encoding.UTF8.GetBytes(linkText);
        linkText = Encoding.UTF8.GetString(bytes);
    
        TextBoxDefinition.SelectedRtf = @"{\rtf1\utf8\field{\*\fldinst HYPERLINK ""file://" + url.Replace("\\", "/") + @""" }{\fldrslt" + linkText + "}}";
    }
}

UPDATE: I forget said. I use .NET framework 4.5.

sadegh
  • 103
  • 5

1 Answers1

0

You need to replace the Persian Unicode characters with their codepoints. For example, using the GetRtfUnicodeEscapedString method from this post, you can insert the link like this:

private void button1_Click(object sender, EventArgs e)
{
    this.richTextBox1.SelectedRtf = @"{\rtf1" +
        @"{\field{\*\fldinst{HYPERLINK https://google.com }}{\fldrslt{" +
        GetRtfUnicodeEscapedString("سلام، من خوبم. تو خوبی؟ چه خبرا؟") +
        @"}}" +
        @"}}";
    this.richTextBox1.LinkClicked += (obj, args) =>
    {
        MessageBox.Show(args.LinkText);
    };
}
static string GetRtfUnicodeEscapedString(string s)
{
    var sb = new StringBuilder();
    foreach (var c in s)
    {
        if (c == '\\' || c == '{' || c == '}')
            sb.Append(@"\" + c);
        else if (c <= 0x7f)
            sb.Append(c);
        else
            sb.Append("\\u" + Convert.ToUInt32(c) + "?");
    }
    return sb.ToString();
}

enter image description here

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398