2013-03-03 108 views
2

我想中斷通過cmd.exe運行的命令。在下面的代碼中,我使用ping www.stackoverflow.com -t作爲示例。發送CTRL_C/SIGINT到C#進程#

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(); 
    } 

從GenerateConsoleCtrlEvent錯誤代碼6.

我按照從操作的指令:

  1. Can I send a ctrl-C (SIGINT) to an application on Windows?

  2. http://pastebin.com/vQuWQD8F

  3. How to send keys instead of characters to a process?

但是,我無法中斷該過程。

任何幫助不勝感激,

回答

0

這可以是具有發送鍵,以及一些其它消息,嚮應用非常普遍的問題。請記住,如果您發送的應用程序比您的程序具有更高的權限評估,它通常不會成功發送密鑰或消息。嘗試在管理權限下運行程序。或者,如果您正在通過Visual Studio進行調試,請在管理權限下運行Visual Studio。

編輯:

看到如何,這是不是你想看看使用ServiceController類記錄here您的問題。它允許比Process更好的控制,並強烈建議在這些情況下的可靠性。我將留下我以前的答案,只是因爲它的一個共同的問題,別人可能會覺得有用的

這裏有兩個教程,讓你開始:

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/

希望這可以幫助你!

+0

謝謝,但這不是我的問題。只是確認以管理員身份運行Visual Studio – Leon 2013-03-03 00:19:09

+0

@Leon請參閱我的編輯^ – FrostyFire 2013-03-03 00:39:10

+0

我真的很希望能夠發送組合鍵,所以我具有靈活性。這似乎是可能的,但我只是做錯了什麼。 – Leon 2013-03-03 02:22:09