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://www.zgcwkj.com/archives/198.html
轉載聲明:請注明本文章的標題及內容的出處和聲明,謝謝
灰色背景布局細節了哦
嘿嘿,搞起來!