您的位置:首页 > 其它

C # 调用外部程序方法

2011-07-04 11:30 525 查看
this.openFileDialog.ShowDialog();
this.txtFileName.Text = this.openFileDialog.FileName;
ProcessStartInfo info = new ProcessStartInfo();

info.FileName = txtFileName.Text;//外部程序名称

//设置外部程序工作目录
info.WorkingDirectory = txtFileName.Text.ToString().Substring(0, this.txtFileName.Text.LastIndexOf("\\"));

this.WorkingDirectory.Text = info.WorkingDirectory;

Process process;
try
{
process = Process.Start(info);//启动外部程序
}
catch (Win32Exception exception)
{
MessageBox.Show("系统找不到指定的程序文件:" + exception.Message);
return;
throw;
}
this.startTime.Text = process.StartTime.ToString();//外部程序运行开始时间

process.WaitForExit(3000);//设置等待3秒后由主程序进行关闭外部程序

if (process.HasExited == false)
{
this.exitType.Text = "由主程序强制终止外部程序运行";
process.Kill();//强制关闭外部程序
this.endTime.Text = DateTime.Now.ToString();
}
else
{
this.exitType.Text = "外部程序正常退出";
this.endTime.Text = process.ExitTime.ToString();//外部程序执行结束退出时间
}


监测外部程序是否退出:

process.EnableRaisingEvents = true;
process.Exited += new EventHandler(process_Exited);

public void process_Exited(object sender, EventArgs e)
{
MessageBox.Show("已监测到外部程序退出。");
}


另外:

监测外部程序是否退出的两个方法:以运行系统记事本为例

方法一:这种方法会阻塞当前进程,直到运行的外部程序退出
System.Diagnostics.Process exep = System.Diagnostics.Process.Start(@"C:\Windows\Notepad.exe");
exep.WaitForExit();//关键,等待外部程序退出后才能往下执行
MessageBox.Show("Notepad.exe运行完毕");

方法二:为外部进程添加一个事件监视器,当退出后,获取通知,这种方法时不会阻塞当前进程,你可以处理其它事情
System.Diagnostics.Process exep = new System.Diagnostics.Process();
exep.StartInfo.FileName = @"C:\Windows\Notepad.exe";
exep.EnableRaisingEvents = true;
exep.Exited += new EventHandler(exep_Exited);
exep.Start();

//exep_Exited事件处理代码,这里外部程序退出后激活,可以执行你要的操作
void exep_Exited(object sender, EventArgs e)
{
MessageBox.Show("Notepad.exe运行完毕");
}


Demo下载
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: