【问题标题】:C# - Live read a batch file in a (rich)textboxC# - 实时读取(丰富)文本框中的批处理文件
【发布时间】:2017-10-31 13:17:26
【问题描述】:

在我的 Windows 窗体程序中,我想实时读取批处理文件。搜索后,我找到了方法。但它只适用于控制台。如果我用richtextbox.appendtext 等替换console.writefile,它会显示“InvalidOperationException”。

这是我的代码

var process = new Process
        {
            StartInfo =
            {
                WorkingDirectory = @"C:\Users\Rayan\Desktop",
                FileName = "cmd.exe",
                Arguments =  "/c test.bat",
                CreateNoWindow = true,
                RedirectStandardOutput = true,
                RedirectStandardInput = true,                  
                UseShellExecute = false           
            }
        };

        process.OutputDataReceived += (s, e) => { richTextBox1.AppendText(e.Data + "\n"); };
        process.Start();
        process.BeginOutputReadLine();
        process.WaitForExit();

我测试了很多东西,但没有任何效果。谢谢你的帮助, 聚甲基。

【问题讨论】:

标签: c# batch-file command-line


【解决方案1】:

我猜是因为你在不同的线程中访问 UI-Control (richTextBox1)。 UI-Controls 只能在 UI 线程中访问。但是您可以调用访问权限。我自己没有测试过,但我认为它应该可以防止 InvalidOperationException。

process.OutputDataReceived += (s, e) => { 
    richTextBox1.BeginInvoke(delegate() {
        richTextBox1.AppendText(e.Data + "\n");
    });
};

【讨论】:

    猜你喜欢
    • 2011-05-21
    • 1970-01-01
    • 1970-01-01
    • 2013-09-14
    • 1970-01-01
    • 2015-11-02
    • 2012-02-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多