Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi-color TextBox C#

I want show text in textbox in 2 colors, for example 1 line red 2 blue, if I use name.ForeColor = Color.Red; all text change color, but I want that will change only 1 line color.

like image 927
Wizard Avatar asked May 14 '12 16:05

Wizard


3 Answers

Use a RichTextBox for that, here is an extension method by Nathan Baulch

public static class RichTextBoxExtensions
{
    public static void AppendText(this RichTextBox box, string text, Color color)
    {
        box.SelectionStart = box.TextLength;
        box.SelectionLength = 0;

        box.SelectionColor = color;
        box.AppendText(text);
        box.SelectionColor = box.ForeColor;
    }
}

Read more here

like image 61
animaonline Avatar answered Nov 06 '22 23:11

animaonline


You need to use a RichTextBox.

You can then change the textcolor by selecting text and changing the selection color or font.

richTextBox1.SelectionFont = new Font("Verdana", 12, FontStyle.Bold);
richTextBox1.SelectionColor = Color.Red;
like image 45
John Koerner Avatar answered Nov 06 '22 23:11

John Koerner


Here is an example with a Fontdialog and Colordialog.

void TextfarbeToolStripMenuItemClick(object sender, EventArgs e)
        {
            colorDialog1.ShowDialog();
            richTextBox1.ForeColor = colorDialog1.Color;
            listBox1.ForeColor = colorDialog1.Color;
        }

        void FontsToolStripMenuItemClick(object sender, EventArgs e)
        {
            fontDialog1.ShowDialog();
            richTextBox1.Font = fontDialog1.Font;
            listBox1.Font = fontDialog1.Font;
        }

        void HintergrundfarbeToolStripMenuItemClick(object sender, EventArgs e)
        {
            colorDialog1.ShowDialog();
            richTextBox1.BackColor = colorDialog1.Color;
            listBox1.BackColor = colorDialog1.Color;
        }
like image 28
berta Avatar answered Nov 06 '22 22:11

berta