1. 程式人生 > >C# 公共控制元件之richTextBox

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、顯示效果