0、功能描述
在C#中调用另一个exe文件;参数通过面板上的控件进行设置输出。面板如下,其中,"加载文件"用于选择要调用的exe文件;“加载图片”、“OdrWidth”、“OdrHeight”用于设置被调用的exe的三个传输参数。
1、代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
namespace EpsonWarpAdjust
{
public partial class Form1 : Form
{
OpenFileDialog Fp_Picture = new OpenFileDialog();
OpenFileDialog Fp_ExeObj = new OpenFileDialog();
public Form1()
{
InitializeComponent();
}
private void SelectPictureObj_Click(object sender, EventArgs e) /*“浏览”的点击事件,用于选择作为参数的图片*/
{
Fp_Picture.Filter = "(jpg)|*.jpg";
if (Fp_Picture.ShowDialog() == DialogResult.OK)
{
textOfPicturePath.Text = Fp_Picture.FileName.ToString(); /*在文件选择框内显示文件路径*/
}
}
private void SelectExeObj_Click(object sender, EventArgs e) /*“浏览”的点击事件,用于选择exe文件*/
{
Fp_ExeObj.Filter = "(exe)|*.exe";
if (Fp_ExeObj.ShowDialog() == DialogResult.OK)
{
textOfExePath.Text = Fp_ExeObj.FileName.ToString(); /*在文件选择框内显示文件路径*/
}
}
private void StartButton_Click(object sender, EventArgs e) /*“开始”的点击事件,用于调用指定的exe文件*/
{
string[] arg = new string[3];
arg[0] = Fp_Picture.FileName; /*被调用的exe的参数*/
arg[1] = OdrWidth.Text;
arg[2] = OdrHeight.Text;
StartProcess(textOfExePath.Text, arg);
}
private void Form1_Load(object sender, EventArgs e)
{
textOfExePath.Text = System.Environment.CurrentDirectory + "\\offsets.exe"; /*初始值设为当前路径下的offset.exe*/
}
public bool StartProcess(string filename, string[] args)
{
try
{
string output;
string parameters = "";
int Index = args[0].LastIndexOf("\\"); /*获取路径名结束下标(不包含文件名)*/
string PathOfBin = args[0].Substring(0, Index); /*获取路径名*/
txtReceive.Text = "文件生成路径:\n" + PathOfBin;
foreach (string arg in args)
{
parameters = parameters + '"' + arg + '"' + " ";/*将每个参数加上双引号,防止参数中带有空格带来的错误*/
}
parameters = parameters.Trim();
Process myprocess = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo(filename,parameters);
myprocess.StartInfo = startInfo;
myprocess.StartInfo.UseShellExecute = false; /*要重定向IO流,Process对象必须将UseShellExecute属性设置为false*/
myprocess.StartInfo.RedirectStandardInput = true; /*标准输入流的重定向,重定向至Process*/
myprocess.StartInfo.RedirectStandardOutput = true; /*标准输出流的重定向,*/
myprocess.StartInfo.RedirectStandardError = true;
myprocess.Start();
myprocess.WaitForExit();
output = myprocess.StandardOutput.ReadToEnd();
if (output.Contains("SUCCESS")) /*判断exe的调用是否成功("SUCCESS"是被调用的exe的标准流输出(如"printf()中的内容"))*/
{
/*弹出提示选择框;若用户选择是的话,进行路径跳转*/
DialogResult result = MessageBox.Show("转换完成,是否跳转到文件生成路径", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
if (result == DialogResult.OK)
{
Process.Start(PathOfBin);
}
else
{
}
}
else
{
MessageBox.Show("转换未完成\n"+"请检查OdrWidth与OdrHeigth的参数", "错误提示");
}
return true;
}
catch (Exception ex)
{
MessageBox.Show("启动应用程序时出错!原因:" + ex.Message);
}
return false;
}
}
}