RichTextBox 和特殊字符 c# [英] RichTextBox and special chars c#
问题描述
我需要将 RTF 格式的文本放入 Richtextbox 中,我尝试将其与 richtextbox.rtf = TextString
参数一起放入,但问题是该字符串具有特殊字符,而richtextbox 没有没有正确显示所有字符串.我正在使用的字符串和代码:
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):
╔===这只是一个例子,特殊字符可能会改变===╗
C# 代码:
String TextString = System.Text.Encoding.UTF8.GetString(TextBytes);
String TextRTF = @"{\rtf1\ansi " + TextString + "}";
richtextbox1.Rtf = TextRTF;
使用这段代码,richtextbox 显示+---这只是一个例子,特殊字符可能会改变---+",在某些情况下,显示??????".
With this code, richtextbox show "+---This is only an example, the special characters may change---+" and in some cases, show "??????".
我该如何解决这个问题?如果我将 \rtf1\ansi
更改为 \rtf1\utf-8
,我看不到更改.
How can i solve this problem? if i change \rtf1\ansi
to \rtf1\utf-8
, i not see changes.
推荐答案
您可以简单地使用 Text
属性:
You can simply use the Text
property:
richTextBox1.Text = "╔═══This is only an example, the special characters may change═══╗";
如果您想使用 RTF
属性:看看这个问题:How to output unicode string to RTF(使用 C#)
If you want to use the RTF
property:
Take a look at this question: How to output unicode string to RTF (using C#)
您需要使用类似这样的方法将特殊字符转换为 rtf 格式:
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();
}
然后使用:
richtextbox1.Rtf = GetRtfUnicodeEscapedString(TextString);
这篇关于RichTextBox 和特殊字符 c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!