繁体   English   中英

使用来自 DataReceivedEventHandler 函数的字符串更新主窗体的文本框控件?

[英]Updating mainform's textbox control with string from DataReceivedEventHandler function?

我正在使用 microsoft 的示例使用异步方法处理 stdout 和 stderr: https : //docs.microsoft.com/en-us/dotnet/api/system.diagnostics.datareceivedeventhandler? view = net-5.0

但是,如何在主窗体中更新文本框的文本属性? 因为,它不允许线程在另一个线程中更新控制。 即,我希望下面的这个处理程序更新 frmMain.txtBox1.text 以在文本框中显示标准输出日志。

    private static void SortOutputHandler(object sendingProcess,
        DataReceivedEventArgs outLine)
    {
        // Collect the sort command output.
        if (!String.IsNullOrEmpty(outLine.Data))
        {
            numOutputLines++;

            // Add the text to the collected output.
            sortOutput.Append(Environment.NewLine +
                $"[{numOutputLines}] - {outLine.Data}");
        }
    }

假设frmMain是一个有效实例(并指向屏幕上已经显示的表单),并且txtBox1已将其修饰符属性更改为 public 以便可见,您可以执行以下操作:

frmMain.txtBox1.Invoke((MethodInvoker) delegate {
    // ... put code in here ...
});

如果 frmMain 字面上是您的 Form 类型的名称,则您需要获取对显示在屏幕上的 frmMain 实际实例的引用。 有多种方法可以做到这一点,包括迭代打开的表单,或者可能事先从其他地方传入该实例。

暂无
暂无

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

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