C# 让程序带参数运行 如:1.exe -a
这个例子演示的是Winform窗体带参数运行,看明白这个了。
那看命令行的小case~
建立好了项目文件后,需要修改的地方有两点!
1:修改 Program 类中的Main方法 加上入口点,并且将参数传递到Form1窗体
2:修改 Form1窗体的构造函数,允许传参。
下面是截图:

下面是代码:
Program.cs代码如下:
namespace ParameterApp
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1(args));
        }
    }
}
Form1代码如下:
namespace ParameterApp
{
    public partial class Form1 : Form
    {
        string[] args;
        public Form1(string[] args)
        {
            this.args = args;
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            if (args.Length != 0)
            {
                MessageBox.Show("第一个参数:" + args[0] + "\n\n一共有:" + args.Length + " 个参数");
            }
            else
            {
                MessageBox.Show("该程序没有带参数运行!");
            }
        }
    }
}
若以上代码编译有问题,可以直接下载我上传的项目包:http://download.csdn.net/source/3495261
本文出自 小古Blog,转载时请注明出处及相应链接。
本文永久链接: http://blog.chdz1.com/?post=151