C#帶參數運行方法
來源:互聯網
上載者:User
比如
aa.exe -auto
aa.exe -main
兩組尾碼,要求分別運行aa的某個線程,比如aa.exe -auto開啟from1,aa.exe -main開啟from2
由於需要修改Program的Main方法,需要更加謹慎,因為一個結構清晰的Main對於後期維護是一個很好的協助。以下的代碼將解析參數,構造啟動表單,啟動表單三個邏輯分割為三個方法Code
1 static class Program
2 {
3 /// <summary>
4 /// The main entry point for the application.
5 /// </summary>
6 [STAThread]
7 static void Main(string[] Args)
8 {
9
10 Application.EnableVisualStyles();
11 Application.SetCompatibleTextRenderingDefault(false);
12 //啟動有預設啟動表單構造器構造出來的啟動表單
13 Application.Run(StartFormCreator(ParseArgsForFormlabel(Args)));
14 }
15
16 //從參數中解析啟動表單參數
17 static string ParseArgsForFormlabel(string[] args)
18 {
19 string formLable = string.Empty;
20 //如果參數數量大於0則截取第一個參數,否則傳回值為string.Empty
21 if (args.Length > 0)
22 {
23 formLable = args[0];
24 }
25 return formLable;
26 }
27 //根據啟動表單參數構造對應的表單
28 static Form StartFormCreator(string Label)
29 {
30 //如果參數是-auto則構造Form1,否則為Form2
31 if (Label.ToLower() == "-auto")
32 {
33 return new Form1();
34 }
35 else
36 {
37 return new Form2();
38 }
39 }
40 }