我有以下代码来格式化添加到RichTextBox控件的行:
rtb.SelectionFont = new Font(new FontFamily("Microsoft Sans Serif"), 14, FontStyle.Bold);
rtb.SelectionColor = Color.SteelBlue;
rtb.SelectionAlignment = HorizontalAlignment.Center;
rtb.AppendText("This is the message to display");
rtb.AppendText(Environment.NewLine);
rtb.SelectionFont = new Font(new FontFamily("Microsoft Sans Serif"), 10, FontStyle.Regular);
rtb.SelectionColor = Color.Black;
rtb.SelectionAlignment = HorizontalAlignment.Left;
rtb.AppendText("This is the log message");
它生成以下RTF字符串:
Microsoft无衬线;}{\f1\fnil\fcharset0 Microsoft Sans Serif;}}{\colortbl;\红色70\绿色130\蓝色180;\red0\green0\blue0;}\viewkind4\uc1\pard\cf1\b\f0\fs28这是display\cf2\b0\fs20\par这是的日志信息
如果我用RTF扩展名保存该字符串,并在写字板中打开文档,我会得到预期的结果,但在应用程序中没有应用这些格式。
我丢失的控件中有设置吗?
谢谢你,
更新:按照LarsTech的建议修改了代码。现在对齐有效,但字体格式仍然无效
更新:原因是运行代码的位置。包含富文本框的用户控件具有Initialize在Load事件之前调用的函数。这阻止了正在应用的格式。一旦我将RTF字符串保存到本地变量,并在Load事件处理程序中使用它格式化工作正常。将LarstTech标记为他的评论的答案确实解决了对齐问题。谢谢大家
您需要添加换行符:
rtb.AppendText("This is the message to display");
rtb.AppendText(Environment.NewLine);
并删除您的手动换行符:
//rtb.AppendText("rnThis is the log message");
rtb.AppendText("This is the log message");
SelectionAlignment需要在设置换行符后应用。在您的代码中,换行发生得太晚了。
rtb.Rtf = //Your rtf string
或者,如果您实际正在加载RTF file
,则可以使用LoadFile
public void LoadMyFile()
{
// Create an OpenFileDialog to request a file to open.
OpenFileDialog openFile1 = new OpenFileDialog();
// Initialize the OpenFileDialog to look for RTF files.
openFile1.DefaultExt = "*.rtf";
openFile1.Filter = "RTF Files|*.rtf";
// Determine whether the user selected a file from the OpenFileDialog.
if(openFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK &&
openFile1.FileName.Length > 0)
{
// Load the contents of the file into the RichTextBox.
richTextBox1.LoadFile(openFile1.FileName);
}
}
保存和加载RTF文件,下面的代码必须工作,或者使用@lll-answerLoadMyFile((方法手动打开RTF文件。
//Save to rtf file
rtb.SaveFile("e:\aaaa.rtf");
//or
System.IO.File.WriteAllText( "e:\aaaa.rtf",rtb.Rtf,System.Text.ASCIIEncoding.ASCII);//without BOM signature.
// end of save to rtf
//Load from rtf file.
rtb.LoadFile("e:\aaaa.rtf");
//or
rtb.Rtf = System.IO.File.ReadAllText("e:\aaaa.rtf", System.Text.ASCIIEncoding.ASCII);
//end of load rtf from file