question

MrCheese-8474 avatar image
0 Votes"
MrCheese-8474 asked Castorix31 commented

C# Run a long CMD process with live output on form

I am sure this question is answered out there somewhere, but I am not having much success with this.
I am seeking to have a long CMD.exe process to run, and show the live output to a Windows Form.
All the solutions I am finding all seem to have to wait for the process to complete, and then output is redirected text at the end.
I am not having any luck working out how to show the progress while it is running, and being notified when completed.
I have tried many variations, but not having any luck yet.
So simply looking to run this code below, and see progress on the WinForm, and then raise an event when the command is completed.

Process process = new Process();
process.StartInfo.FileName="cmd.exe";
process.StartInfo.Arguments=@"/C DIR C:\ /s";

I found a working solution using SetParent, MoveWindow, SetWindowLong functions from user32.dll, but I can't control the CMD Windows appearance.

Looking for a simple (elegant) way to achieve this result so I can see the progress, and control the position, fonts and colours as well.

Again, I know solutions are around, but finding this more complicated than what I would like.
Thanks for any suggestions.

not-supported
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

Castorix31 avatar image
2 Votes"
Castorix31 answered Castorix31 commented

You can use a BackgroundWorker
For example, this adds the result of the command in a RichTextBox richTextBox1 =>

Pfff, I cannot post code on those bugged forums, so I post a jpg of the code I tested =>
(change C:\Temp, that I used to check when it was finished )

asynccode.jpg




· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

What on earth is ControlInvoke ?

0 Votes 0 ·

It was just a utility function :

     delegate void VoidDelegate();
     public static void ControlInvoke(System.Windows.Forms.Control control, Action function)
     {
         if (control.IsDisposed || control.Disposing)
             return;

         if (control.InvokeRequired)
         {
             control.Invoke(new VoidDelegate(() => ControlInvoke(control, function)));
             return;
         }
         function();
     }
0 Votes 0 ·