Multi-color TextBox C#

2019-01-15 18:35发布

问题:

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.

回答1:

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;


回答2:

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



回答3:

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;
        }


回答4:

First of all, the details + tags you provided are not sufficient - C# doesn't have one specific UI framework, it has a few: WPF, Winforms, ASP.NET, Silverlight.

Second of all, you can not do this with a regular textbox control in any of the above. You will need to find/create a custom UI control which has a different behaviour or use a more advanced control e.g. a rich text box.