简体   繁体   English

将控制台输入和输出重定向到文本框

[英]Redirect console input and output to a textbox

Hi there and thanking in advance 嗨,在此先感谢

I am trying (very hard) to redirect Console input and output into a textbox. 我正在尝试(非常努力)将控制台输入和输出重定向到文本框中。 So far output is working fine but the trouble is with input. 到目前为止,输出工作正常,但问题出在输入上。 For example I cannot execute a simple program that will do the following: 例如,我无法执行将执行以下操作的简单程序:

Console.WriteLine("Please enter your name: "); Console.WriteLine(“请输入您的姓名:”); string name = Console.ReadLine(); 字符串名称= Console.ReadLine(); Console.WriteLine("Hi there " + name); Console.WriteLine(“ Hi there” + name);

The reason I can't achieve this is because that the program has to stop while waiting for user to type his/her name and press enter. 我之所以无法实现,是因为该程序必须在等待用户键入其名称并按Enter时停止。 If I wait for user input on a new thread then the main GUI thread freezes and the textbox can never receive the KeyPress. 如果我在新线程上等待用户输入,则主GUI线程将冻结,文本框将永远无法收到KeyPress。 This thing has me totally stumped. 这件事让我完全难过。 Any advice (or better still code) would be greatly appreciated. 任何建议(或者更好的代码)将不胜感激。

Cheers 干杯

The code below is a Console app that calls another console app to do some work and not a WinForm app, but you could easily replace the event handlers (TransformProcessOutputDataReceived, and TransformProcessErrorDataReceived) to output to a text box instead of a TextWriter. 下面的代码是一个控制台应用程序,它调用另一个控制台应用程序来执行某些工作,而不是WinForm应用程序,但是您可以轻松替换事件处理程序(TransformProcessOutputDataReceived和TransformProcessErrorDataReceived)以输出到文本框而不是TextWriter。 Unfortunately it doesn't directly address your issue of the called console application waiting for user input. 不幸的是,它不能直接解决您等待用户输入的调用控制台应用程序的问题。 The code below does pump some input to the called console app via standard input, so perhaps you could supply it from your windows app in the same manner. 下面的代码确实通过标准输入将某些输入泵送到调用的控制台应用程序,因此也许您可以以相同的方式从Windows应用程序提供它。

Hope this was helpful, I had a heck of a time getting it to work originally myself, sorry I forgot the original references I had used, it was a while ago. 希望这会有所帮助,我花了一点时间让它本来可以自己工作,但是对不起我忘记了我以前使用的原始参考文献,那是前一段时间。

private static void ProcessRetrievedFiles(List<string> retrievedFiles)
    {
        Console.WriteLine();
        Console.WriteLine("Processing retrieved files:");
        Console.WriteLine("---------------------------");
        Console.WriteLine();
        foreach (string filePath in retrievedFiles)
        {
            if (String.IsNullOrEmpty(filePath)) continue;

            Console.WriteLine(filePath);
            Process transformProcess = new Process();

            string baseOutputFilePath = Path.Combine(ExportDirectory, Path.GetFileNameWithoutExtension(filePath));

            transformProcess.StartInfo.FileName = TransformerExecutablePath;
            transformProcess.StartInfo.Arguments = string.Format(
                "-i:\"{0}\" -x:\"{1}\" -o:\"{2}.final.xml\"",
                filePath,
                string.Empty,
                baseOutputFilePath);
            transformProcess.StartInfo.UseShellExecute = false;
            transformProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            transformProcess.StartInfo.RedirectStandardError = true;
            transformProcess.StartInfo.RedirectStandardOutput = true;
            transformProcess.StartInfo.RedirectStandardInput = true;

            transformProcess.EnableRaisingEvents = true;

            //attach the error/output recievers for logging purposes
            transformProcess.ErrorDataReceived += TransformProcessErrorDataReceived;
            transformProcess.OutputDataReceived += TransformProcessOutputDataReceived;

            ProcessBridgeFileOutputWriter = new StreamWriter(
                    baseOutputFilePath + ".log",
                    false);

            ProcessBridgeFileOutputWriter.AutoFlush = true;

            transformProcess.Start();

            transformProcess.BeginOutputReadLine();
            transformProcess.BeginErrorReadLine();

            //the exe asks the user to press a key when they are done...
            transformProcess.StandardInput.Write(Environment.NewLine);
            transformProcess.StandardInput.Flush();

            //because we are not doing this asynchronously due to output writer
            //complexities we don't want to deal with at this point, we need to 
            //wait for the process to complete
            transformProcess.WaitForExit();

            ProcessBridgeFileOutputWriter.Close();
            ProcessBridgeFileOutputWriter.Dispose();

            //detach the error/output recievers
            transformProcess.ErrorDataReceived -= TransformProcessErrorDataReceived;
            transformProcess.OutputDataReceived -= TransformProcessOutputDataReceived;
        }
    }

    static void TransformProcessOutputDataReceived(object sender, DataReceivedEventArgs e)
    {
        if (!string.IsNullOrEmpty(e.Data))
        {
            ProcessBridgeFileOutputWriter.WriteLine(e.Data);
        }
    }

    static void TransformProcessErrorDataReceived(object sender, DataReceivedEventArgs e)
    {
        if (!string.IsNullOrEmpty(e.Data))
        {
            ProcessBridgeFileOutputWriter.WriteLine(string.Format("ERROR: {0}", e.Data));
        }
    }

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

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