黑马程序员技术交流社区

标题: C#启动外部程序的几种常用方法汇总 [打印本页]

作者: 陈君    时间: 2014-9-2 22:59
标题: C#启动外部程序的几种常用方法汇总
这篇文章主要介绍了C#启动外部程序的几种常用方法汇总,对C#初学者来说有很高的学习借鉴价值,需要的朋友可以参考下
本文汇总了C#启动外部程序的几种常用方法,非常具有实用价值,主要包括如下几种方法:
1. 启动外部程序,不等待其退出。
2. 启动外部程序,等待其退出。
3. 启动外部程序,无限等待其退出。
4. 启动外部程序,通过事件监视其退出。
实现代码如下:
  1. // using System.Diagnostics;
  2. private string appName = "calc.exe";
  3. /// <summary>
  4. /// 1. 启动外部程序,不等待其退出
  5. /// </summary>
  6. private void button1_Click(object sender, EventArgs e)
  7. {
  8. Process.Start(appName);
  9. MessageBox.Show(String.Format("外部程序 {0} 启动完成!", this.appName), this.Text,
  10. MessageBoxButtons.OK, MessageBoxIcon.Information);
  11. }
  12. /// <summary>
  13. /// 2. 启动外部程序,等待其退出
  14. /// </summary>
  15. private void button2_Click(object sender, EventArgs e)
  16. {
  17. try
  18. {
  19. Process proc = Process.Start(appName);
  20. if (proc != null)
  21. {
  22. proc.WaitForExit(3000);
  23. if (proc.HasExited) MessageBox.Show(String.Format("外部程序 {0} 已经退出!", this.appName), this.Text,
  24. MessageBoxButtons.OK, MessageBoxIcon.Information);
  25. else
  26. {
  27. // 如果外部程序没有结束运行则强行终止之。
  28. proc.Kill();
  29. MessageBox.Show(String.Format("外部程序 {0} 被强行终止!", this.appName), this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
  30. }
  31. }
  32. }
  33. catch (ArgumentException ex)
  34. {
  35. MessageBox.Show(ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
  36. }
  37. }
  38. /// <summary>
  39. /// 3. 启动外部程序,无限等待其退出
  40. /// </summary>
  41. private void button3_Click(object sender, EventArgs e)
  42. {
  43. try
  44. {
  45. Process proc = Process.Start(appName);
  46. if (proc != null)
  47. {
  48. proc.WaitForExit();
  49. MessageBox.Show(String.Format("外部程序 {0} 已经退出!", this.appName), this.Text,
  50. MessageBoxButtons.OK, MessageBoxIcon.Information);
  51. }
  52. }
  53. catch (ArgumentException ex)
  54. {
  55. MessageBox.Show(ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
  56. }
  57. }
  58. /// <summary>
  59. /// 4. 启动外部程序,通过事件监视其退出
  60. /// </summary>
  61. private void button4_Click(object sender, EventArgs e)
  62. {
  63. try
  64. {
  65. //启动外部程序
  66. Process proc = Process.Start(appName);
  67. if (proc != null)
  68. {
  69. //监视进程退出
  70. proc.EnableRaisingEvents = true;
  71. //指定退出事件方法
  72. proc.Exited += new EventHandler(proc_Exited);
  73. }
  74. }
  75. catch (ArgumentException ex)
  76. {
  77. MessageBox.Show(ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
  78. }
  79. }
  80. /// <summary>
  81. ///启动外部程序退出事件
  82. /// </summary>
  83. void proc_Exited(object sender, EventArgs e)
  84. {
  85. MessageBox.Show(String.Format("外部程序 {0} 已经退出!", this.appName), this.Text,
  86. MessageBoxButtons.OK, MessageBoxIcon.Information);
复制代码

读者可以根据情况选择本文实例中的方法,希望能对大家的C#程序设计有一定的帮助借鉴作用。




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2