【问题标题】:Send CTRL_C/SIGINT to a process from C#从 C# 向进程发送 CTRL_C/SIGINT
【发布时间】:2013-02-17 07:48:03
【问题描述】:

我想中断通过 cmd.exe 运行的命令。在下面的代码中,我以 ping www.stackoverflow.com -t 为例。

    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?

但是,我无法中断该过程。

非常感谢任何帮助,

【问题讨论】:

    标签: c# console pinvoke


    【解决方案1】:

    在向应用程序发送密钥以及其他一些消息时,这可能是一个非常常见的问题。请记住,如果您发送到的应用程序具有比您的程序更高的权限评估,它通常不会成功发送密钥或消息。尝试在管理权限下运行您的程序。或者,如果您通过 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/

    希望对您有所帮助!

    【讨论】:

    • 谢谢,但这不是我的问题。刚刚确认以管理员身份运行 Visual Studio
    • 我真的很希望能够发送组合键,这样我就有了灵活性。似乎有可能,但我只是做错了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-04
    • 1970-01-01
    • 1970-01-01
    • 2017-10-02
    • 1970-01-01
    • 2010-11-01
    • 1970-01-01
    相关资源
    最近更新 更多