C# 调用外部程序传参数

今天公司让我把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



作者:高调的小丑
链接:https://www.jianshu.com/p/27018255783a
来源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值