首页 文章

WinForms RichTextBox问题

提问于
浏览
-1

我有以下代码来格式化添加到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字符串:

{\ rtf1 \ ansi \ ansicpg1252 \ deff0 \ deflang4105 {\ fonttbl {\ f0 \ fnil Microsoft Sans Serif;} {\ f1 \ fnil \ fcharset0 Microsoft Sans Serif;}} {\ colortbl; \ red70 \ green130 \ blue180; \ red0 \ green0 \ blue0;} \ viewkind4 \ uc1 \ pard \ cf1 \ b \ f0 \ fs28这是要显示的消息\ cf2 \ b0 \ fs20 \ par这是日志消息\ cf0 \ f1 \ fs17 \ par}

如果我使用RTF扩展名保存该字符串并在写字板中打开文档,我会得到预期的结果,但是在应用程序中没有应用格式 .

我失踪了控制中的设置吗?

谢谢,

更新:修改了LarsTech建议的代码 . 现在对齐工作但字体格式仍然没有 . 更新:原因是代码运行的位置 . 包含富文本框的用户控件具有在Load事件之前调用的Initialize函数 . 这阻止了格式化的应用 . 一旦我将RTF字符串保存到局部变量并在Load事件处理程序中使用它,格式化就可以正常工作 . 标记LarstTech作为答案烧烤他的评论确实解决了对齐问题 . 谢谢你们 .

3 回答

  • 0

    您需要添加换行符:

    rtb.AppendText("This is the message to display");
    rtb.AppendText(Environment.NewLine);
    

    并删除您的手动换行符:

    //rtb.AppendText("\r\nThis is the log message");
    rtb.AppendText("This is the log message");
    

    需要在设置换行符后应用SelectionAlignment . 在您的代码中,换行时间太晚了 .

  • 0
    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);
       }
    }
    
  • 2

    保存和加载RTF文件,下面的代码必须工作,或者手动打开RTF文件使用@lll answer LoadMyFile() 方法 .

    //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
    

相关问题