问题
I would like to interrupt a command running through cmd.exe. In the code below, I am using ping www.stackoverflow.com -t as an example.
public void Run()
{
System.Diagnostics.ProcessStartInfo si = new System.Diagnostics.ProcessStartInfo("cmd.exe");
si.RedirectStandardInput = true;
si.RedirectStandardOutput = true;
si.RedirectStandardError = true;
si.UseShellExecute = false;
si.CreateNoWindow = false;
//si.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
System.Diagnostics.Process console = new Process();
console.StartInfo = si;
console.EnableRaisingEvents = true;
console.OutputDataReceived += proc_OutputDataReceived;
console.ErrorDataReceived += proc_ErrorDataReceived;
console.Start();
console.BeginOutputReadLine();
console.BeginErrorReadLine();
console.StandardInput.WriteLine("ping www.stackoverflow.com -t");
Thread.Sleep(4000);
bool success = GenerateConsoleCtrlEvent((uint)0, (uint)console.SessionId);
if (!success)
{
MessageBox.Show("Error Code: " + Marshal.GetLastWin32Error().ToString());
}
char asdf = (char)0x3;
console.StandardInput.WriteLine('\x3');
console.StandardInput.WriteLine(asdf);
console.StandardInput.Write(asdf);
//console.StandardInput.Close();
console.StandardInput.WriteLine(@"exit");
console.WaitForExit();
}
The error code from GenerateConsoleCtrlEvent is 6.
I have followed the instructions from:
Can I send a ctrl-C (SIGINT) to an application on Windows?
http://pastebin.com/vQuWQD8F
How to send keys instead of characters to a process?
However, I am unable to interrupt the process.
Any help greatly appreciated,
回答1:
This can be a very common problem with sending keys as well as some other messages, to an application. Remember, that if the application you are sending to has higher permissions evaluation than your program, it usually will not succeed in sending the keys or message. Try running your program under administrative privileges. Or, if you are debugging through Visual Studio, run Visual Studio under administrative privileges.
EDIT:
seeing as how this is not your problem you want to take a look at using the ServiceController
class documented here. It allows much finer control than Process
does and is highly recommended for reliability in these situations. I will leave my previous answer simply because its a common problem that someone else may find helpful
Here are two tutorials to get you started:
http://www.codeproject.com/Articles/31688/Using-the-ServiceController-in-C-to-stop-and-start http://www.c-sharpcorner.com/uploadfile/mahesh/servicecontroller-in-C-Sharp/
Hope this helps you!
来源:https://stackoverflow.com/questions/15180956/send-ctrl-c-sigint-to-a-process-from-c-sharp