使用扩展方法尝试将AppendText添加到RichTextBox时无效的操作异常

时间:2014-10-06 15:59:42

标签: c# forms richtextbox

我有一个由StackOverflow上的另一个问题提供的RichTextBox的扩展方法。

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

我试图像这样使用它:

public void Write(string Text)
        {
            Color Green = Color.Green;
            TxtBox.AppendText(Text, Green);
        }

但是,当我运行时,我得到了

  

类型' System.InvalidOperationException'的第一次机会异常。   发生在System.Windows.Forms.dll

有没有人知道可能出现什么问题?感谢。

1 个答案:

答案 0 :(得分:3)

您的代码有效,但似乎您尝试从除UI线程以外的其他线程访问您的richtextbox。

您可以按如下方式更改扩展程序:

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

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

    }
}