views:

481

answers:

1

I can't figure out how to simulate sending Ctrl+C to an external program. When I run the program manually through CMD, when I press ctrl+c it will abort and ask me if I want to save before it shuts down completely. I'm trying to simulate this through C# but it doesn't seem to work.

This is what I am doing now:

        // Create new process object
        process = new Process();

        // Setup event handlers
        process.EnableRaisingEvents = true;
        process.OutputDataReceived += OutputDataReceivedEvent;
        process.ErrorDataReceived += ErrorDataReceivedEvent;
        process.Exited += ProgramExitedEvent;

        // Setup start info
        ProcessStartInfo psi = new ProcessStartInfo
        {
            FileName = ExePath,
            UseShellExecute = false, // Must be false to redirect IO
            RedirectStandardOutput = false,
            RedirectStandardError = false,
            RedirectStandardInput = true,
            Arguments = arguments
        };

        process.StartInfo = psi;

        // Start the program
        process.Start();

        process.StandardInput.Write( "\x3" ); // 0x3 is Ctrl+C according to ASCII table

The program doesn't respond to this and just continues. Is the problem that Windows actually doesn't send Ctrl+C to the input stream when doing Ctrl+C in the console, but instead sends an "interrupt" to the process? I thought that sending "\x3" to the input stream is EXACTLY what Windows does when one presses Ctrl+C in the console. Am I wrong?

+1  A: 

This question has been answered on a prior occasion in which I posted a detailed answer on SO here.

tommieb75
That's a nice library you got there but I really need something more platform independent. I also need to be able to actually send the keys directly to the process and not just to the foreground window.
johnrl
@Johnrl: I did not write that library! :) that was written by someone else! :) but I incorporated it into a test rig as shown in the link to prove that it works and can be sent directly to the process...not just any foreground window...by getting the handle of the window, use that to send the keys to that handle!
tommieb75
Problem is that the program I start doesn't have a window since I redirect all it's output into my own program. Therefore sending keys to windows doesn't work.
johnrl
I have found that it actually does work....the proof of concept code just does that...that window is hidden and is not shown....and clicking on the button does actually post the ctrl+c combo to it...and terminates...
tommieb75
@tommieb75 - There's a difference between "the window is hidden" and "there is no window." One of the Process.StartInfo fields is CreateNoWindow, which starts the process but doesn't allocate a window handle. No window handle == no message loop.
David Lively