简体   繁体   English

添加到Form构造函数时,RichTextBox文本着色具有不同的行为

[英]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. 我有一个RichTextBox放在窗体上,我想添加不同的文本与不同的颜色。 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). 我使用此代码将颜色文本添加到RichTextBox,但是当我将它添加到Form构造函数时,它有不同的行为(第一个单词没有着色)。 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 注意:我使用VS2010,.NET 3.5

It seems the reason is Control's Handle has not been created yet. 似乎原因是Control的Handle尚未创建。 It is created only when you first call to AppendText . 它仅在您第一次调用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. 您可以通过请求Handle属性来执行此操作。

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: 将代码移动到Load事件中它将起作用:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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