C# 启动程序并持续输入命令和监听输出的结果
全局变量
Process process = new Process();
启动程序
//新线程启动,不影响别动线程
Task task = Task.Factory.StartNew(() =>
{
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.UseShellExecute = false;//需要对进程执行读写流
startInfo.RedirectStandardOutput = true; //需要获取输出流
startInfo.RedirectStandardInput = true;//需要获取输入流
startInfo.CreateNoWindow = true;//不显示程序窗口
startInfo.WindowStyle = ProcessWindowStyle.Hidden;//隐藏窗口
startInfo.FileName = @"\bedrock_server.exe";
//startInfo.FileName = @"cmd.exe";
process.StartInfo = startInfo;//关联信息
//输出事件
process.OutputDataReceived += Process_OutputDataReceived;
process.Start();
//退出事件
process.Exited += Process_Exited;
//异步读取生成进程的标准输出
//这会为每一行输出引发 OutputDataReceived 事件
process.BeginOutputReadLine();
process.WaitForExit();
});
监听输出事件
private void Process_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
if (!string.IsNullOrEmpty(e.Data))
{
Console.WriteLine(e.Data);
//printString.Invoke(e.Data);
richTextBox1.Invoke(new PrintString((data) =>
{
richTextBox1.Text += data + "\r\n";
}), e.Data);
}
}
输入命令
var writer = process.StandardInput;
writer.WriteLine("tp a");
释放对象
process.Kill();
版权属于:zgcwkj
本文链接:https://zgcwkj.com/archives/198.html
转载声明:请注明本文章的标题及内容的出处和声明,谢谢
灰色背景布局细节了哦
嘿嘿,搞起来!