I have a windows form that executes a batch file. I want to transfer everything that happends in my console to a panel in my form. How can I do this? How can my DOS console comunicate with my windows form panel???
Thanks
You can call the DOS or batch program from your Form application and redirect the output to a string:
using (var p = new System.Diagnostics.Process( ))
{
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = PathToBatchFile;
p.StartInfo.Arguments = args;
p.Start( );
string o = p.StandardOutput.ReadToEnd( );
p.WaitForExit( );
}
The doc states that if you want to read both StandardError and StandardOutput, you need to read at least one of them asynchronously in order to avoid deadlocks.
Also, if you call ReadToEnd on one of the redirected streams, you must do so before calling WaitForExit(). If you WaitForExit before ReadToEnd, the output buffer can fill up, suspending the process, which means it will never exit. That would be a very long wait. This is also in the doc!
example:
string output;
string error;
System.Diagnostics.Process p = new System.Diagnostics.Process
{
StartInfo =
{
FileName = program,
Arguments = args,
WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
UseShellExecute = false,
}
};
if (waitForExit)
{
StringBuilder sb = new StringBuilder();
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
Action<Object,DataReceivedEventArgs> stdErrorRead = (o,e) =>
{
if (!String.IsNullOrEmpty(e.Data))
sb.Append(e.Data);
};
p.ErrorDataReceived += stdErrorRead;
p.Start();
// begin reading stderr asynchronously
p.BeginErrorReadLine();
// read stdout synchronously
output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
// return code is in p.ExitCode
if (sb.Length > 0)
error= sb.ToString();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With