您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

为RichTextBox字符串的不同部分上色

为RichTextBox字符串的不同部分上色

这是一个扩展方法,该AppendText方法使用color参数重载该方法

public static class RichText@R_19_2419@Extensions
{
    public static void AppendText(this RichText@R_19_2419@ @R_19_2419@, string text, Color color)
    {
        @R_19_2419@.SelectionStart = @R_19_2419@.TextLength;
        @R_19_2419@.SelectionLength = 0;

        @R_19_2419@.SelectionColor = color;
        @R_19_2419@.AppendText(text);
        @R_19_2419@.SelectionColor = @R_19_2419@.ForeColor;
    }
}

这就是您将如何使用它:

var userid = "USER0001";
var message = "Access denied";
var @R_19_2419@ = new RichText@R_19_2419@
              {
                  Dock = DockStyle.Fill,
                  Font = new Font("Courier New", 10)
              };

@R_19_2419@.AppendText("[" + DateTime.Now.ToShortTimeString() + "]", Color.Red);
@R_19_2419@.AppendText(" ");
@R_19_2419@.AppendText(userid, Color.Green);
@R_19_2419@.AppendText(": ");
@R_19_2419@.AppendText(message, Color.Blue);
@R_19_2419@.AppendText(Environment.NewLine);

new Form {Controls = {@R_19_2419@}}.ShowDialog();

请注意,如果输出大量消息,您可能会注意到闪烁。有关如何减少RichText@R_19_2419@闪烁的想法,请参见C#Corner文章

其他 2022/1/1 18:14:12 有706人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶