標籤:
在編寫程式時經常會使用到調用可執行程式的情況,本文將簡單介紹C#調用exe的方法。在C#中,通過Process類來進行進程操作。 Process類在System.Diagnostics包中。
樣本一
using System.Diagnostics;Process p = Process.Start("notepad.exe");p.WaitForExit();//關鍵,等待外部程式退出後才能往下執行
通過上述代碼可以調用記事本程式,注意如果不是調用系統程式,則需要輸入全路徑。
樣本二
當需要調用cmd程式時,使用上述調用方法會彈出令人討厭的黑窗。如果要消除,則需要進行更詳細的設定。
Process類的StartInfo屬性包含了一些進程啟動資訊,其中比較重要的幾個
FileName 可執行程式檔案名稱
Arguments 程式參數,已字串形式輸入
CreateNoWindow 是否不需要建立視窗
UseShellExecute 是否需要系統shell調用程式
通過上述幾個參數可以讓討厭的黑屏消失
System.Diagnostics.Process exep = new System.Diagnostics.Process();exep.StartInfo.FileName = binStr;exep.StartInfo.Arguments = cmdStr;exep.StartInfo.CreateNoWindow = true;exep.StartInfo.UseShellExecute = false;exep.Start();exep.WaitForExit();//關鍵,等待外部程式退出後才能往下執行
或者
System.Diagnostics.Process exep = new System.Diagnostics.Process();System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();startInfo.FileName = binStr;startInfo.Arguments = cmdStr;startInfo.CreateNoWindow = true;startInfo.UseShellExecute = false;exep.Start(startInfo);exep.WaitForExit();//關鍵,等待外部程式退出後才能往下執行
C#調用Exe程式樣本