如何将 ctrl+c 发送到 c# 中的进程? [英] How do I send ctrl+c to a process in c#?

查看:48
本文介绍了如何将 ctrl+c 发送到 c# 中的进程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为命令行可执行文件编写包装类.这个 exe 接受来自 stdin 的输入,直到我在命令提示符 shell 中点击 Ctrl+C,在这种情况下,它会根据输入.我想在 C# 代码中模拟 Ctrl+C 按下,将 kill 命令发送到 .NET Process 对象.我试过调用 Process.Kill(),但这在进程的 StandardOutput StreamReader 中似乎没有给我任何信息.可能有什么我做错的吗?这是我尝试使用的代码:

I'm writing a wrapper class for a command line executable. This exe accepts input from stdin until I hit Ctrl+C in the command prompt shell, in which case it prints output to stdout based on the input. I want to simulate that Ctrl+C press in C# code, sending the kill command to a .NET Process object. I've tried calling Process.Kill(), but that doesn't seem to give me anything in the process's StandardOutput StreamReader. Might there be anything I'm not doing right? Here's the code I'm trying to use:

ProcessStartInfo info = new ProcessStartInfo(exe, args);
info.RedirectStandardError = true;
info.RedirectStandardInput = true;
info.RedirectStandardOutput = true;
info.UseShellExecute = false;
Process p = Process.Start(info);

p.StandardInput.AutoFlush = true;
p.StandardInput.WriteLine(scriptcode);

p.Kill();

string error = p.StandardError.ReadToEnd();
if (!String.IsNullOrEmpty(error)) 
{
    throw new Exception(error);
}
string output = p.StandardOutput.ReadToEnd();

输出总是空的,即使我在手动运行 exe 时从 stdout 取回数据.

The output is always empty, even though I get data back from stdout when I run the exe manually.

编辑:顺便说一下,这是 C# 2.0.

Edit: This is C# 2.0 by the way.

推荐答案

实际上我刚刚想出了答案.谢谢你们的回答,但事实证明我所要做的就是:

I've actually just figured out the answer. Thank you both for your answers, but it turns out that all i had to do was this:

p.StandardInput.Close()

这导致我生成的程序完成从标准输入读取并输出我需要的内容.

which causes the program I've spawned to finish reading from stdin and output what i need.

这篇关于如何将 ctrl+c 发送到 c# 中的进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆