【问题标题】:Updating mainform's textbox control with string from DataReceivedEventHandler function?使用 DataReceivedEventHandler 函数中的字符串更新主窗体的文本框控件?
【发布时间】:2021-12-05 20:42:50
【问题描述】:

我正在使用 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}");
        }
    }

【问题讨论】:

标签: c# winforms


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多