天天看点

C#带参数运行方法

比如

aa.exe -auto

aa.exe -main

两组后缀,要求分别运行aa的某个线程,比如aa.exe -auto打开from1,aa.exe -main打开from2

由于需要修改Program的Main方法,需要更加谨慎,因为一个结构清晰的Main对于后期维护是一个很好的帮助。以下的代码将解析参数,构造启动窗体,启动窗体三个逻辑分割为三个方法

C#带参数运行方法
C#带参数运行方法

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     }