简体   繁体   中英

RichTextBox text coloring has different behavior when added to the Form constructor

I have a RichTextBox placed on a form and i want to add different text with different colors to it. I used this code to add color text to the RichTextBox, but it has a different behavior when i add it to the Form constructor( the first word is not colored). can any one explain this different behavior?

Here's the code:

        richTextBox1.Font = new Font("Consolas", 18f, FontStyle.Bold);
        richTextBox1.BackColor = Color.AliceBlue;
        string[] words =
        {
        "Dot",
        "Net",
        "Perls",
        "is",
        "a",
        "nice",
        "website."
        };
        Color[] colors =
        {
        Color.Aqua,
        Color.CadetBlue,
        Color.Cornsilk,
        Color.Gold,
        Color.HotPink,
        Color.Lavender,
        Color.Moccasin
        };
        for (int i = 0; i < words.Length; i++)
        {
        string word = words[i];
        Color color = colors[i];
        {
            richTextBox1.SelectionBackColor = color;
            richTextBox1.AppendText(word);
            richTextBox1.SelectionBackColor = Color.AliceBlue;
            richTextBox1.AppendText(" ");
        }
        }

Note: I use VS2010,.NET 3.5

It seems the reason is Control's Handle has not been created yet. It is created only when you first call to AppendText . though it shouldn't be a problem(I'll get back if I find why that's a problem).

To fix it, just force the creation of handle. You do this by requesting the Handle property.

var handle = richTextBox1.Handle;//Force create handle
for (int i = 0; i < words.Length; i++)
{
    string word = words[i];
    Color color = colors[i];

    richTextBox1.SelectionBackColor = color;
    richTextBox1.AppendText(word);
    richTextBox1.SelectionBackColor = Color.AliceBlue;
    richTextBox1.AppendText(" ");

}

Move the code into the Load event and it will work:

    private void Form1_Load(object sender, EventArgs e)
    {
        colorTbx();
    }

    private void colorTbx()
    {
        //your code here
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM