【WinForm】杂记(4):C#编写和调用exe程序(带参数)

背景

有时调用exe时,需要外部给定一个参数,作为该exe程序的输入变量。这需要在exe编写时就考虑输入变量,同时也要在调用时改写代码。

编写exe程序部分,主要分成两步:

第一步. 给Main函数添加参数

找到以Visual Studio为例,找到解决方案资源管理器,如图1

其中Program.cs就包含调用该exe程序时的Main函数,选择并右键选中查看代码、进入代码编辑界面,改写为如下代码:

static void Main(string[] args)
 {
     Application.EnableVisualStyles();
     Application.SetCompatibleTextRenderingDefault(false);
     Application.Run(new FrmMain(args));
}

  

其中string[] args就是外部调用时需要给定的输入变量。为了保证程序运行安全,可以再添加其它的代码

static void Main(string[] args)
{
    if (args == null || args.Length < 1) {
        MessageBox.Show("Please give an input string!");
        Application.Exit();
    } else {
        try {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new FrmMain(args));
        } catch {
            MessageBox.Show("Some errors exist during exe is running!");
        }
    }
}

这里注意到输入变量的类型可以根据需要调节,也可以输入多个变量但是在正式传入的时候(第10行)只选择部分,这些都要根据项目实际情况而定。

第二步. 在窗口中接收传入的参数

再图1中找到FrmMain.cs(一般项目创建时,默认是Form1.cs),选择并右键选中查看代码、进入代码编辑界面,改写为如下代码

public partial class FrmMain : Form
{
    public FrmMain(string[] args)
    {
        InitializeComponent();
        s = args;
    }
    string[] s;
}

这里的第3行就对应上段代码的第10行(没有改写这段代码前,上段代码的第10行会报错)。从外部传入变量args后,在窗体程序中定义一个全局变量s来接收args的值,使得窗体在初始化时就被赋值。这里的全局变量s最好是私有的。

s被赋值后就可以在窗体中参与代码运行了。

编写调用exe程序的代码

新建一个工程文件,后台写入如下代码

 1 public void ExecuteCommandSync(string filename, string[] args)
 2 {
 3     string s = "";
 4     foreach (string arg in args) {
 5         s = s + arg + " ";//using " " to split parameters
 6     }
 7     s = s.Trim();//delete " " of head and tail
 8     try {
 9         System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
10 
11         startInfo.ErrorDialog = false;
12         startInfo.UseShellExecute = false;
13         startInfo.RedirectStandardOutput = true;
14         startInfo.RedirectStandardError = true;
15         System.Diagnostics.Process process = new System.Diagnostics.Process();
16         startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Maximized;
17         startInfo.CreateNoWindow = true;
18 
19         startInfo.FileName = filename;//exe file name
20         startInfo.Arguments = s;//parameters
21         process.StartInfo = startInfo;
22         process.Start();
23         process.WaitForExit(1000);
24     } catch (Exception objException) {
25         throw new Exception("Problem to execute outer .exe file!", objException);
26     }
27 }
View Code

 特别注意的情况是,调用程序时传入多个参数:实际传入参数时数量只能是一个(否则第20行代码会报错),所以多个参数之间用空格分隔开(见第4-6行代码)

猜你喜欢

转载自www.cnblogs.com/RicardoIsLearning/p/12111201.html