C#调用外部应用程序

来源:互联网 发布:我家门前有两棵树 知乎 编辑:程序博客网 时间:2024/04/30 14:03

演示说明
      此示例演示如何用C#代码调用记事本程序(Notepad.exe)。主程序等待7秒钟,如果用户没有关闭记事本程序,则主程序强制关闭。


示例代码

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Text;  
  4.   
  5. // 需要引用的命名空间。  
  6. using System.Diagnostics;  
  7.   
  8. namespace InvokeProgram  
  9. {  
  10.     class Program  
  11.     {  
  12.         static void Main(string[] args)  
  13.         {  
  14.             // 声明一个程序信息类。  
  15.             System.Diagnostics.ProcessStartInfo StartInfo = new ProcessStartInfo();  
  16.   
  17.             // 设置外部程序名。  
  18.             StartInfo.FileName = "notepad.exe";  
  19.   
  20.             // 设置外部程序的启动参数(命令行参数)。  
  21.             StartInfo.Arguments = "HelloWord.txt";  
  22.   
  23.             // 设置外部程序工作目录。  
  24.             StartInfo.WorkingDirectory = @"C:\";  
  25.   
  26.             // 声明一个程序类。  
  27.             System.Diagnostics.Process Proc = new Process();  
  28.   
  29.             try  
  30.             {  
  31.                 // 启动外部程序。  
  32.                 Proc = System.Diagnostics.Process.Start(StartInfo);  
  33.             }  
  34.             catch (System.ComponentModel.Win32Exception e)  
  35.             {  
  36.                 Console.WriteLine("系统找不到指定的程序文件。\r{0}", e);  
  37.                 return;  
  38.             }  
  39.   
  40.             // 打印出外部程序的开始执行时间。  
  41.             Console.WriteLine("外部程序的开始执行时间:{0}", Proc.StartTime);  
  42.   
  43.             // 等待7秒钟。  
  44.             Proc.WaitForExit(7000);  
  45.   
  46.             // 如果这个外部程序没有结束运行则对其强行终止。  
  47.             if (Proc.HasExited == false)  
  48.             {  
  49.                 Console.WriteLine("由主程序强行终止外部程序的运行!");  
  50.                 Proc.Kill();  
  51.             }  
  52.             else  
  53.             {  
  54.                 Console.WriteLine("由外部程序正常退出!");  
  55.             }  
  56.   
  57.             Console.WriteLine("外部程序的结束运行时间:{0}", Proc.ExitTime);  
  58.             Console.WriteLine("外部程序在结束运行时的返回值:{0}", Proc.ExitCode);  
  59.         }  
  60.     }  
  61. }  

0 0
原创粉丝点击