简体   繁体   English

可以在异步任务中更改前景色但不能更改文本框的背景色

[英]Can change forecolor but not backcolor of textbox in async task

I'm trying to change colors of a textbox as stated above, I'm just gonna show the code because I think that would be the most fitting explanation.我正在尝试更改 colors 如上所述的文本框,我只是要显示代码,因为我认为这将是最合适的解释。

    private async Task Disco()
    {
        int duration;
        switch (ptr)
        {
            default:
                //duration = 900;//15 min
                duration = 10;
                break;
            case 1:
                duration = 50;
                //duration = 1800;//30 min
                break;
        }

        int color = 0;
        await Task.Run(() =>
        {
            while (duration-- != 0)
            {
                TB.ForeColor = foreground[color];
                TB.BackColor = background[color];
                if (++color == foreground.Length)
                    color = 0;
                Thread.Sleep(1000);
            }
        });

        TB.ForeColor = Color.Black;
    }

The forecolor has been working fine, but when I added the backcolor line it throws前景色一直工作正常,但是当我添加背景线时它抛出

"An exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll but was not handled in user code Cross-thread operation not valid: Control 'TB' accessed from a thread other than the thread it was created on." “在 System.Windows.Forms.dll 中发生类型为‘System.InvalidOperationException’的异常,但未在用户代码中处理跨线程操作无效:控件‘TB’是从创建它的线程以外的线程访问的。”

How is this even possible???这怎么可能???

I'm literally accessing it in the line above with the forecolor, why is the backcolor behaving different???我实际上是在上面的行中使用前景色访问它,为什么背景色表现不同???

If I make the backcolor line a comment everything is fine again....如果我将背景色线作为评论,一切都会好起来....

Making a static var for the textbox does not help.为文本框制作 static var 没有帮助。

I am using .net 3.1(for win 7) but that should not be the problem here.我正在使用 .net 3.1(用于 win 7),但这不应该是这里的问题。

As hijinxbassist and MySkullCaveIsADarkPlace stated, I got lot lucky with the foreground and had to invoke the UI calls.正如 hijinxbassist 和 MySkullCaveIsADarkPlace 所说,我很幸运地看到了前台,不得不调用 UI 调用。

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

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