/*********************************************************
* 功 能:通過C#程式調用 Windows 記事本程式 編輯
* 名為 test.txt 的文字檔。
*
* 在整個程式中 System.Diagnostics.Process.Start(Info)
* 為語句。
* 只是單獨執行一個外部程式,可用一條如下代碼即可:
* System.Diagnostics.Process.Start(
* "外部程式名","啟動參數");
*
*********************************************************/
1 using System;
2
3 class test
4 {
5 static void Main()
6 {
7
8 //聲明一個程式資訊類
9 System.Diagnostics.ProcessStartInfo Info = new System.Diagnostics.ProcessStartInfo();
10
11 //設定外部程式名
12 Info.FileName = "notepad.exe";
13
14 //設定外部程式的啟動參數(命令列參數)為test.txt
15 Info.Arguments = "test.txt";
16
17 //設定外部程式工作目錄為 C:\
18 Info.WorkingDirectory = "C:\\";
19
20 //聲明一個程式類
21 System.Diagnostics.Process Proc ;
22
23 try
24 {
25 //
26 //啟動外部程式
27 //
28 Proc = System.Diagnostics.Process.Start(Info);
29 }
30 catch(System.ComponentModel.Win32Exception e)
31 {
32 Console.WriteLine("系統找不到指定的程式檔案。\r{0}", e);
33 return;
34 }
35
36 //列印出外部程式的開始執行時間
37 Console.WriteLine("外部程式的開始執行時間:{0}", Proc.StartTime);
38
39 //等待3秒鐘
40 Proc.WaitForExit(3000);
41
42 //如果這個外部程式沒有結束運行則對其強行終止
43 if(Proc.HasExited == false)
44 {
45 Console.WriteLine("由主程式強行終止外部程式的運行!");
46 Proc.Kill();
47 }
48 else
49 {
50 Console.WriteLine("由外部程式正常退出!");
51 }
52 Console.WriteLine("外部程式的結束已耗用時間:{0}", Proc.ExitTime);
53 Console.WriteLine("外部程式在結束運行時的傳回值:{0}", Proc.ExitCode);
54 }
55 }