C# 公共控件之richTextBox

1、添加控件

2、添加代码 button1(颜色),button2(字体),button3(查看效果)

// 直接接口更改 字体和颜色
// AppendTextColorful(richTextBox1, string.Format("图像显示操作!"), 10, Color.Blue, true);
//private void AppendTextColorful(RichTextBox rtBox, string text, float fontSize, Color color, bool addNewLine = true)
//{
//    if (addNewLine)
//    {
//        text += Environment.NewLine;
//    }
//    rtBox.SelectionStart = rtBox.TextLength;
//    rtBox.SelectionLength = 0;
//    rtBox.SelectionColor = color;
//    rtBox.SelectionFont = new Font(
//        "宋体",
//        fontSize,
//        FontStyle.Bold
//    );
//    rtBox.AppendText(text);
//    rtBox.SelectionColor = rtBox.ForeColor;
//}

private void AppendTextColorful(RichTextBox rtBox, string text, Font font, Color color, bool addNewLine = true)
{
    if (addNewLine)
    {
        text += Environment.NewLine;
    }
    rtBox.SelectionStart = rtBox.TextLength;
    rtBox.SelectionLength = 0;
    rtBox.SelectionColor = color;
    rtBox.SelectionFont = font;
    rtBox.AppendText(text);
}

private void button1_Click(object sender, EventArgs e)
{
    ColorDialog colorDia = new ColorDialog();
    if (colorDia.ShowDialog() == DialogResult.OK)
    {
        //获取所选择的颜色
        Color colorChoosed = colorDia.Color;
        button1.BackColor = colorChoosed;
        richTextBox1.SelectionColor = colorChoosed;
    }
}

private void button2_Click(object sender, EventArgs e)
{
    FontDialog fontDialog1 = new FontDialog();
    DialogResult result = fontDialog1.ShowDialog();
    if (result == DialogResult.OK)
    {
        button2.Font = fontDialog1.Font;
        richTextBox1.SelectionFont = fontDialog1.Font;
    }
}

private void button3_Click(object sender, EventArgs e)
{
    AppendTextColorful(richTextBox1, string.Format("落霞与孤鹜齐飞,秋水共长天一色"), richTextBox1.SelectionFont, richTextBox1.SelectionColor, true);
}

3、显示效果