我正在尝试将给定PID的任何进程的输出指向我的表单上的文本框,例如cmd.exe
我使用以下代码但没有发生任何事情:
public partial class FormMain : Form
{
private Int32 PID = 0;
private Process process;
public FormMain()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
PID = Convert.ToInt32(textBox2.Text);
process = Process.GetProcessById(PID);
process.OutputDataReceived += process_OutputDataReceived;
}
void process_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
textBox1.Text += e.Data;
}
private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
{
process.OutputDataReceived -= process_OutputDataReceived;
}
}
我做错了什么?
答案 0 :(得分:0)
我认为您尝试做的事情的问题在于您使用该事件的方式。该事件仅在异步输出操作期间触发。
您必须设置:
process.StartInfo.RedirectStandardOutput = true;
然后使用异步读取操作来触发事件:
process.BeginOutputReadLine();
您应该阅读该活动的文档:
http://msdn.microsoft.com/en-us/library/system.diagnostics.process.outputdatareceived.aspx