摘要:[C#] 啟動應用程式並且傳入參數
Introduction
有時候我們會使用一個啟動器去檢查有沒有最新的應用程式,檢查完了,就要啟動應用程式,
並且傳入相關的資訊;這邊小弟紀錄自己的方法,若是有其他方法,希望前輩們指教。
Example
sample1 : 啟動表單應用程式
1.表單程式碼
Program.cs
namespace ApplicationDemo {
    static class Program {
        /// <summary>
        /// 應用程式的主要進入點。
        /// </summary>
        [STAThread]
        //加入傳入參數
        static void Main(string[] args) {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);           
            if (args.Length == 0) {
                Application.Run(new Form1());
            } else {
                Application.Run(new Form1(args[0].ToString()));
            }
        }
    }
}
Form1.cs
namespace ApplicationDemo {
    public partial class Form1 : Form {
        private string _args;
        public Form1() {
            InitializeComponent();
        }
        public Form1(string value) {
            InitializeComponent();
            if (!string.IsNullOrEmpty(value)) {
                _args = value;
            }
        }
        private void btnShowArgs_Click(object sender, EventArgs e) {
            MessageBox.Show(_args);
        }
    }
}
2.啟動器程式碼
class Program {
        static void Main(string[] args) {
            //指定應用程式路徑
            string target = Environment.CurrentDirectory + @"\ApplicationDoem.exe";
            //方法一
            //Process.Start(target, "我是參數");
            //方法二
            ProcessStartInfo pInfo = new ProcessStartInfo(target);
            pInfo.Arguments = "我是參數";
            using (Process p = new Process()) {            
                p.StartInfo = pInfo;
                p.Start();
            }
            Console.ReadKey();
        }
    }
執行結果
sample2 : 啟動 Console 應用程式
1.欲啟動的應用程式碼
namespace StartConsoleApplication {
    class Program {
        static void Main(string[] args) {
            if (args != null && args.Length > 0) {
                //印出程式的名稱
                Console.WriteLine(AppDomain.CurrentDomain.FriendlyName);
                //印出傳入的參數
                Console.WriteLine(args[0].ToString());
            }
            Console.ReadKey();
        }
    }
}
2.欲啟動的應用程式碼
namespace ConsoleApplication20091226 {
    class Program {
        static void Main(string[] args) {
            //指定應用程式路徑
            //string target = Environment.CurrentDirectory + @"\ApplicationDoem.exe";
            string target = Environment.CurrentDirectory + @"\StartConsoleApplication.exe";
            //方法一
            //Process.Start(target, "我是參數");
            //方法二
            ProcessStartInfo pInfo = new ProcessStartInfo(target);
            pInfo.Arguments = "我是參數";
            using (Process p = new Process()) {            
                p.StartInfo = pInfo;
                p.Start();
            }
            Console.ReadKey();
        }
    }
}執行結果
Link
Process 成員
System.Diagnostics 命名空間
Start
ProcessStartInfo
CloseMainWindow
Kill
ProcessThread
完整程式碼
ConsoleApplication20091226.rar
三小俠 小弟獻醜,歡迎指教

