C#调用外部应用程序创建者:光脚丫思考创建时间:7/23/2009 9:30:38 PM
演示说明 此示例演示如何用C#代码调用记事本程序(Notepad.exe)。主程序等待7秒钟c;如果用户没有关闭记事本程序c;则主程序强制关闭。
示例代码
code" class="tags" href="/tags/CLASS.html" title=class>class="c-sharp">using System; using System.Collections.Generic; using System.Text; // 需要引用的命名空间。 using System.Diagnostics; namespace InvokeProgram { class="tags" href="/tags/CLASS.html" title=class>class Program { static void Main(class="tags" href="/tags/CLASS.html" title=class>class="tags" href="/tags/STRING.html" title=string>string[] args) { // 声明一个程序信息类。 System.Diagnostics.ProcessStartInfo StartInfo = new ProcessStartInfo(); // 设置外部程序名。 StartInfo.FileName = "notepad.exe"; // 设置外部程序的启动参数(命令行参数)。 StartInfo.Arguments = "HelloWord.txt"; // 设置外部程序class="tags" href="/tags/GongZuo.html" title=工作>工作目录。 StartInfo.WorkingDirectory = @"C:/"; // 声明一个程序类。 System.Diagnostics.Process Proc = new Process(); try { // 启动外部程序。 Proc = System.Diagnostics.Process.Start(StartInfo); } catch (System.ComponentModel.Win32Exception e) { Console.WriteLine("系统找不到指定的程序文件。/r{0}", e); return; } // 打印出外部程序的开始执行时间。 Console.WriteLine("外部程序的开始执行时间:{0}", Proc.StartTime); // 等待7秒钟。 Proc.WaitForExit(7000); // 如果这个外部程序没有结束运行则对其强行终止。 if (Proc.HasExited == false) { Console.WriteLine("由主程序强行终止外部程序的运行!"); Proc.Kill(); } else { Console.WriteLine("由外部程序正常退出!"); } Console.WriteLine("外部程序的结束运行时间:{0}", Proc.ExitTime); Console.WriteLine("外部程序在结束运行时的返回值:{0}", Proc.ExitCode); } } }