C# 實現自動執行命令

@zgcwkj  2022年11月30日

分類:

默認 

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();


評論已關閉

  1. 灰色背景布局細節了哦

    1. @馬同學的博客

      嘿嘿,搞起來!

Top