Answered Dialogue with CLI Process

TM74

New member
Joined
Aug 27, 2020
Messages
2
Programming Experience
1-3
Hi everyone,

I want to run a process in the windows console, after that, I want to pass (with button click) some commands and see the result in a RichTextBox.

I’m able to launch the program and read the responses after starting, but when I’m trying to send any commands, it doesn’t work. I’m not able to “speak” with the process…
So, if you have any ideas in order to write in the process, I will take it with pleasure !
I already tried :
C#:
Console.WriteLine
and
C#:
StandardInput
.

Below the code :
C#:
public 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}");
        //RichTextBox
        MCM.ActiveForm.Invoke(MCM.AffichageTextDelegate, new object[] { outLine.Data });
    }
}

public static async Task<int> RunProcessAsync() {
    using (var process = new Process {
        StartInfo = {
            FileName = "AAA.exe",
            Arguments = “-v COM74",
            UseShellExecute = false,
            CreateNoWindow = false,
            RedirectStandardOutput = true,
            RedirectStandardInput = true,
            RedirectStandardError = true
        },
        EnableRaisingEvents = true
    })
    { return await RunProcessAsync(process).ConfigureAwait(false); }

}

private static Task<int> RunProcessAsync(Process process) {

    var tcs = new TaskCompletionSource<int>();
    process.Exited += (s, ea) => tcs.SetResult(process.ExitCode);
    process.OutputDataReceived += (s, ea) => Console.WriteLine(ea.Data);
    sortOutput = new StringBuilder();
    process.OutputDataReceived += SortOutputHandler;
    process.ErrorDataReceived += (s, ea) => Console.WriteLine("ERR: " + ea.Data);

    process.Start();
    process.BeginOutputReadLine();
    process.BeginErrorReadLine();

    return tcs.Task;
}

private async void Btn_Click(object sender, EventArgs e) {
    await RunProcessAsync();
 
For your first attempt, don't confuse yourself with async/await's. Just follow the synchronous sample code in the documentation:



Once you get the communication working, then slowly applying asynchronicity if you really need it. Personally, I think that all you would need is async/await on a Task.Start() where the task that is being started is synchronous. If async/await is really confusing you, use an BackgroundWorker instead.
 
Thx for your reply !
It's ok with a synchronous process.


C#:
        public static Process myProcess;
        public static StreamWriter myStreamWriter;
 
Back
Top Bottom