如果你要運(yùn)行一個(gè)命令行程序,或者打開(kāi)一個(gè)windows應(yīng)用程序,或者打開(kāi)默認(rèn)的web瀏覽器或email客戶端,你應(yīng)該如何在你的C#代碼中實(shí)現(xiàn)這個(gè)功能呢?
以下這些例子完成相同的任務(wù),你可以使用System.Diagnostics.Process中的類和方法完成這些任務(wù),甚至作的更多。 例1:不管輸出結(jié)果,僅僅是運(yùn)行一個(gè)命令行程序:
private void simpleRun_Click(object sender, System.EventArgs e){ System.Diagnostics.Process.Start(@"C:\listfiles.bat"); }
例2. 得到程序運(yùn)行結(jié)果等待直到程序中止(同步運(yùn)行程序)
private void runSyncAndGetResults_Click(object sender, System.EventArgs e){
System.Diagnostics.ProcessStartInfo psi =new System.Diagnostics.ProcessStartInfo(@"C:\listfiles.bat");
psi.RedirectStandardOutput = true;
psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
psi.UseShellExecute = false;
System.Diagnostics.Process listFiles;
listFiles = System.Diagnostics.Process.Start(psi);
System.IO.StreamReader myOutput = listFiles.StandardOutput;
listFiles.WaitForExit(2000);
if (listFiles.HasExited)
{
string output = myOutput.ReadToEnd();
this.processResults.Text = output;
}
}
例3. 使用用戶機(jī)器里的默認(rèn)瀏覽器顯示URL
private void launchURL_Click(object sender, System.EventArgs e){
string targetURL = @http://www.;
System.Diagnostics.Process.Start(targetURL);
}
|