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下载
相关文章推荐
- Android中外部程序调用方法总结
- 调用外部程序的方法
- Shark中调用外部程序的方法
- 外部程序调用应用Activity方法简介
- 关于flash调用外部程序的方法
- Shark中调用外部程序的方法
- 关于用外部程序调用Informatica Workflow的方法
- QT中调用外部程序的方法
- java调用外部程序的方法
- VC中调用外部EXE程序方法
- vc弹屏的两种方法(调用外部程序)
- c#调用外部程序方法
- c++调用外部程序方法
- 调用外部程序的方法
- QT中调用外部程序的方法 QProcess类
- 使用Qprocess的startDetached()方法调用外部exe程序
- SilverLight浏览器交互之:SilverLight程序调用外部Html中的Javascript方法(附源码)
- PHP调用外部程序的方法
- 调用外部程序的方法
- QT调用外部程序有下面几种方法: