简单掌握Windows中C#启动外部程序进程的方法
许多用户在程序开发过程中需要使用C#启动一个外部程序(进程),在使用完毕该外部程序后,又希望能将其关闭。我们特在此对C#启动和关闭外部进程的方法进行一个简单的介绍。
C#启动外部程序(进程)有两种方法:一种是直接使用C#提供的Process类,利用类的函数操作来直接启动外部程序;另一种方法是使用传统的Win32API函数CreateProcess来实现外部进程的启动。
使用C#提供的Process类来启动外部程序方法比较简单,例举代码如下:
usingSystem.Diagnostics;//包含了Process类的定义 intmyprocessID;//进程ID //方法一:直接使用.Net提供的Process类来实现外部程序的启动 privatevoidopenButton_Click(objectsender,EventArgse) { ProcessmyProcess=Process.Start('\\NandFlash\\SerialTST.exe','');//启动外部进程 myprocessID=myProcess.Id;//获得该外部进程ID } 使用传统的Win32API函数的方法相对复杂,代码如下: usingSystem.Runtime.InteropServices;//使用外部Win32API #regionWin32APICreateProcess函数声明做函数申明。 [DllImport('coredll.Dll',EntryPoint='CreateProcess',SetLastError=true)] externstaticintCreateProcess(stringstrImageName,stringstrCmdLine, IntPtrpProcessAttributes,IntPtrpThreadAttributes, intbInheritsHandle,intdwCreationFlags, IntPtrpEnvironment,IntPtrpCurrentDir, IntPtrbArray,ProcessInfooProc); publicclassProcessInfo { publicinthProcess; publicinthThread; publicintProcessID; publicintThreadID; } #endregion
方法二:使用Win32API来实现外部程序的启动
privatevoidopenButton_Click(objectsender,EventArgse) { ProcessInfopi=newProcessInfo(); CreateProcess('\\NandFlash\\SerialTST.exe','',IntPtr.Zero,IntPtr.Zero, 0,0,IntPtr.Zero,IntPtr.Zero,IntPtr.Zero,pi); myprocessID=pi.ProcessID;//得到该程序的ID } 关闭外部进程的方法就是直接通过获得的该外部进程的ID来关闭它。这里只介绍使用.Net的Process类的方法: //关闭外部进程 privatevoidcloseButton_Click(objectsender,EventArgse) { ProcessmyProcessA=Process.GetProcessById(myprocessID);//通过ID关联进程 myProcessA.Kill();//kill进程 }