在編寫程序時(shí)經(jīng)常會(huì)使用到調(diào)用可執(zhí)行程序的情況,本文將簡單介紹C#調(diào)用exe的方法。在C#中,通過Process類來進(jìn)行進(jìn)程操作。 Process類在System.Diagnostics包中。
示例一
using System.Diagnostics;
Process p = Process.Start("notepad.exe");
p.WaitForExit();//關(guān)鍵,等待外部程序退出后才能往下執(zhí)行
通過上述代碼可以調(diào)用記事本程序,注意如果不是調(diào)用系統(tǒng)程序,則需要輸入全路徑。
示例二
當(dāng)需要調(diào)用cmd程序時(shí),使用上述調(diào)用方法會(huì)彈出令人討厭的黑窗。如果要消除,則需要進(jìn)行更詳細(xì)的設(shè)置。
Process類的StartInfo屬性包含了一些進(jìn)程啟動(dòng)信息,其中比較重要的幾個(gè)
FileName 可執(zhí)行程序文件名
Arguments 程序參數(shù),已字符串形式輸入
CreateNoWindow 是否不需要?jiǎng)?chuàng)建窗口
UseShellExecute 是否需要系統(tǒng)shell調(diào)用程序
通過上述幾個(gè)參數(shù)可以讓討厭的黑屏消失
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();//關(guān)鍵,等待外部程序退出后才能往下執(zhí)行
或者
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();//關(guān)鍵,等待外部程序退出后才能往下執(zhí)行