今天公司让我把Winform程序里的一块单独成一个exe文件,从原程序中打开新的exe程序,这就涉及到参数的传递,故来记录下传递参数到exe程序的方式
第一种方式
首先在程序A中添加引用using System.Diagnostics;
string strA = "hello" + "," + "world";Process pro = Process.Start(@"C:\testB.exe", strA);//打开程序B pro.WaitForExit();int Result = pro.ExitCode;//程序B退出回传值if (Result == 1)//接收到程序B退出代码"1" {textBox1.Text = "退出程序B";}
在程序B中的Program.cs
static void Main(string[] args){Application.EnableVisualStyles();Application.SetCompatibleTextRenderingDefault(false);try{FormB.str = args[0].Trim();//用一个字符串来接收FormA中传过来的数据Application.Run(new Form1());}catch (Exception ex){MessageBox.Show(ex.Message);}}
这样的话在B程序Form1中就接收到了程序A中传过来的字符串strA
//将传过来的数据放到textbox中textBox1.Text =str;
效果.png
若点击退出按钮,退出系统时发生指定代码,且这种退出方式是完全退出。
Environment.Exit(1);程序B退出回传"1"
效果.png
第二种方式
System.Diagnostics.Process pro = new System.Diagnostics.Process();pro.StartInfo.FileName = @"C:\testB.exe";//传入4个字符串pro.StartInfo.Arguments = string.Format("{0} {1} {2} {3}", "hello", "world", "你好", "世界");pro.Start();//开启程序
程序B中的
static void Main(string[] args){Application.EnableVisualStyles();Application.SetCompatibleTextRenderingDefault(false);Application.Run(new Form1(args));//也可以像第一种那样实现}
FormB页面中
public static string[] temp;public Form1(string[] args){InitializeComponent();temp = args;//因为传过来的是一个数组,所以我们定义了一个新的全局空数组来接替他 }//将传过来的数据放到textbox中textBox1.Text =temp[0]+temp[1]+temp[2]+temp[3];
FormB页面.png
作者:高调的小丑
链接:/p/27018255783a