C# 啟動EXE文件及帶啟動參數EXE


(一)、先制作一個帶啟動參數的EXE文件。

 步驟: 

           1、定義全局私有變量:private string[] s = new string[1];  //這里為了簡單起見,只做一個參數

           2、  在窗體的構造函數中初始化啟動參數            

public Form1(string[] p)
        {
            InitializeComponent();
            s = p;
        }

          3、在main()函數中進行參數判斷        

static void Main(string[]   args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            if (args.Length <= 0)
            {
                MessageBox.Show("請輸入啟動參數");
                Application.Exit();
            }
            if (args.Length == 1)
            {
                if (args[0] == "Test")
                {
                    Application.Run(new Form1(args));
                }
                else
                {
                    MessageBox.Show("啟動參數錯誤,請輸入Test");
                    Application.Exit();
                }
            }
        }

到這里,帶啟動參數的EXE文件制作完成 

(二)調用帶參數EXE文件(調用剛才做的程序),我寫了下面這個簡單的函數        

public bool StartProcess(string filename, string[] args)
        {
            try
            {
                string s="";
                foreach(string arg in args)
                {
                s=s+arg+" ";
                }
                s=s.Trim();
                Process myprocess = new Process();
                ProcessStartInfo startInfo = new ProcessStartInfo(filename,s);
                myprocess.StartInfo = startInfo;

//通過以下參數可以控制exe的啟動方式,具體參照 myprocess.StartInfo.下面的參數,如以無界面方式啟動exe等
                myprocess.StartInfo.UseShellExecute = false;
                myprocess.Start();
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show("啟動應用程序時出錯!原因:" + ex.Message);
            }
            return false;
        }

接着,在調用的地方調用此函數        

private void button1_Click(object sender, EventArgs e)
        {
            string[] arg = new string[1];
            arg[0] = textBox1.Text.Trim();
            StartProcess(@"E:/ZHOUXL/C#/FileOP/FileOP/bin/Debug/FileOP.exe",arg);
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM