3

I need to put text with RTF format in a richtextbox, I try to put it with the richtextbox.rtf = TextString parameter, but the problem is that the string has special chars and the richtextbox does not show all the string correctly. The String and code that I am using:

String (TextString):

╔═══This is only an example, the special characters may change═══╗

C# Code:

String TextString = System.Text.Encoding.UTF8.GetString(TextBytes);
String TextRTF = @"{\rtf1\ansi " + TextString + "}";
richtextbox1.Rtf = TextRTF;

With this code, richtextbox show "+---This is only an example, the special characters may change---+" and in some cases, show "??????".

How can i solve this problem? if i change \rtf1\ansi to \rtf1\utf-8, i not see changes.

Jerry
  • 4,258
  • 3
  • 31
  • 58
Manux22
  • 323
  • 1
  • 5
  • 16
  • _I need to put text with RTF format in a richtextbox, I try to put it with the richtextbox.rtf = TextString parameter_ You problem with fonts aside: You really should manipulate the Rtf of a RTB only when it is really necessary. See [here for the rules](http://stackoverflow.com/questions/30295523/how-do-i-send-varying-text-sized-strings-from-one-richtextbox-to-another/30296255?s=2|0.1630#30296255) of how to change RTB content! – TaW May 21 '15 at 06:02

1 Answers1

5

You can simply use the Text property:

richTextBox1.Text = "╔═══This is only an example, the special characters may change═══╗";

If you want to use the RTF property: Take a look at this question: How to output unicode string to RTF (using C#)

You need to use something like this to convert the special characters to rtf format:

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();
}

Then use:

richtextbox1.Rtf = GetRtfUnicodeEscapedString(TextString);
Community
  • 1
  • 1
Jerry
  • 4,258
  • 3
  • 31
  • 58