Controlling another process's console with C#

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
I am writing a program that will start and control the process for aconsole application (folding@homes console if anyone is interested)and I have all but two things working.

First off, I am capturingthe output just fine but, the console window for fah.exe still comes upand stays open until the process ends (albeit it is blank the entiretime).

My second problem is that when I try to send a CTRL-C tothe process to shut it down I get an error code 6 (which, after someresearch seems to be ERROR_INVALID_HANDLE) and the process neverreceives the command.

Here is the code where I start theprocess. Another note, this is called from a Thread, otherwise theoutput does not get sent to my program until after the process exits.

[background=white]
1private Process p; 2private ProcessStartInfo proc; 3 4private void StartFAH() 5{ 6 7    proc = new ProcessStartInfo(); 8    proc.FileName = @"C:FAH SMPfah.exe"9    proc.RedirectStandardInput = true10    proc.RedirectStandardOutput = true11    proc.UseShellExecute = false12    p = Process.Start(proc); 13    string res; 14 15    while (!p.HasExited) 16    { 17 18        res = p.StandardOutput.ReadLine(); 19        consoleOutput.Invoke(new EventHandler(delegate 20        { 21            consoleOutput.SelectedText = string.Empty; 22            consoleOutput.SelectionFont = new Font(consoleOutput.SelectionFont, FontStyle.Bold); 23            consoleOutput.AppendText(res + "n"); 24            consoleOutput.ScrollToCaret(); 25        })); 26 27 28    } 29    p.Close(); 30 31} [/background]

And here is the code for the CTRL-C.

[background=white]
1[DllImport("kernel32.dll", SetLastError=true)] 2static extern bool GenerateConsoleCtrlEvent(ConsoleCtrlEvent sigevent, int dwProcessGroupId); 3 4public enum ConsoleCtrlEvent 5{ 6    CTRL_C = 0, 7    CTRL_BREAK = 1, 8    CTRL_CLOSE = 2, 9    CTRL_LOGOFF = 5, 10    CTRL_SHUTDOWN = 6 11} 12 13 14private void butCtrlC_Click(object sender, EventArgs e) 15{ 16    if (GenerateConsoleCtrlEvent(ConsoleCtrlEvent.CTRL_C, p.Id)) 17        MessageBox.Show("Successfully sent"); 18    else 19        MessageBox.Show("Error Code: " + Marshal.GetLastWin32Error().ToString()); 20 21} [/background]

If you have any other suggestions, please dont hold back.

View the full article
 
Back
Top