让一个WINFORM程序接收启动参数,用处很多,比如可以用于识别程序是双击打开的还是开机启动的。
下面有个例子,需求是让一个WINFORM程序在开机启动的时候接收一个叫做“auto”的参数,如果有这个参数,就做个什么事情。
第一步打开项目里的 Program.cs 文件,默认的程序入口点是这样:
[STAThread] static void Main(string[] args) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); }
把它改成,这个可以是多个,是一个字符串数组:
[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个参数就行,下面是窗体程序代码的改动:
public Form1() { InitializeComponent(); } public Form1(string[] args) { InitializeComponent(); this.args = args; if(this.args[0] == "auto") { //这里写要做的事情 } }