2012年4月19日 星期四

Form間傳參數(C#)

由於測試程式 (以下稱 A) 需模擬成多台真實程式測試其效能。有一種方法是測試程式當作一個物件,程式開啟時依照設定創造多個物件出來以達到其效果。當然另一種更簡單的方法是撰寫另一隻程式 (以下稱 B) 呼叫執行測試程式並傳入不同參數達到。
以下是 B 程式參數傳入 Function 撰寫:
private void btnRun_Click(object sender, EventArgs e)
        {
            // 參數值
            int StartPort = Convert.ToInt32(txtSPort.Text);
            // 模擬數量
            int VirtualNum = Convert.ToInt32(txtVNum.Text);
            // 跑回圈的方式開啟多台
            for (int i = StartPort; i < StartPort+VirtualNum; i++)
            {
                // 要開啟的程式名稱寫在這
                string exename = "APLoadTesting.exe";

                string target = Application.StartupPath + @"\" + exename;                
                
                ProcessStartInfo pInfo = new ProcessStartInfo(target);
                // 要傳的參數寫在這
                pInfo.Arguments = i.ToString();
                using (Process p = new Process())
                {
                    p.StartInfo = pInfo;
                    p.Start();
                }

                // 避免開啟程式共用資料會錯亂
                Thread.Sleep(2000);
            }                                  
        }
A程式之Program.cs中的Application.Run改成以下方式:
static void Main(string[] Args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            //有參數則接參數的方式開啟
            if (Args.Length > 0)
            {
                Application.Run(new Form1(Args[0]));
            }             
            else//無參數傳入則正常開啟
            {
                Application.Run(new Form1());
            }            
        }
A程式的Form1.cs加入以下程式:
public Form1(string EQPID)//EQPID為傳進來的參數
        {
            InitializeComponent();            
            txtIP.Text = "127.0.0.1";
            txtPort.Text = EQPID;
            txtEQID.Text = EQPID;
        }

沒有留言:

張貼留言