溫馨提示×

C#中如何創(chuàng)建子進程

c#
小樊
84
2024-08-27 09:54:09
欄目: 編程語言

在C#中,可以使用System.Diagnostics.Process類來創(chuàng)建子進程

using System;
using System.Diagnostics;

class Program
{
    static void Main()
    {
        // 創(chuàng)建一個新的ProcessStartInfo對象,用于指定要啟動的子進程的相關信息
        ProcessStartInfo startInfo = new ProcessStartInfo
        {
            // 設置要啟動的應用程序的文件名(包括路徑)
            FileName = "notepad.exe",
            
            // 設置是否使用操作系統(tǒng)shell來啟動進程
            UseShellExecute = true,
            
            // 設置是否在新窗口中啟動進程
            CreateNoWindow = false
        };

        try
        {
            // 使用Process.Start方法啟動子進程
            using (Process process = Process.Start(startInfo))
            {
                Console.WriteLine("子進程已啟動,ID: " + process.Id);
                
                // 等待子進程退出
                process.WaitForExit();
                
                Console.WriteLine("子進程已退出,退出碼: " + process.ExitCode);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("啟動子進程時發(fā)生錯誤: " + ex.Message);
        }
    }
}

在這個示例中,我們創(chuàng)建了一個新的ProcessStartInfo對象,并設置了要啟動的應用程序的文件名(包括路徑)。然后,我們使用Process.Start方法啟動子進程,并等待其退出。最后,我們輸出子進程的退出碼。

0