簡單掌握Windows中C#啟動(dòng)外部程序進(jìn)程的方法
許多用戶在程序開發(fā)過程中需要使用C#啟動(dòng)一個(gè)外部程序(進(jìn)程),在使用完畢該外部程序后,又希望能將其關(guān)閉。我們特在此對(duì)C#啟動(dòng)和關(guān)閉外部進(jìn)程的方法進(jìn)行一個(gè)簡單的介紹。
C#啟動(dòng)外部程序(進(jìn)程)有兩種方法:一種是直接使用C#提供的Process類,利用類的函數(shù)操作來直接啟動(dòng)外部程序;另一種方法是使用傳統(tǒng)的Win32 API函數(shù)CreateProcess來實(shí)現(xiàn)外部進(jìn)程的啟動(dòng)。
使用C#提供的Process類來啟動(dòng)外部程序方法比較簡單,例舉代碼如下:
using System.Diagnostics; // 包含了Process類的定義 int myprocessID; // 進(jìn)程ID // 方法一:直接使用.Net提供的Process類來實(shí)現(xiàn)外部程序的啟動(dòng) private void openButton_Click(object sender, EventArgs e) { Process myProcess = Process.Start('\\NandFlash\\SerialTST.exe', ''); // 啟動(dòng)外部進(jìn)程 myprocessID = myProcess.Id; // 獲得該外部進(jìn)程ID } 使用傳統(tǒng)的Win32 API函數(shù)的方法相對(duì)復(fù)雜,代碼如下: using System.Runtime.InteropServices; // 使用外部Win32 API #region Win32 API CreateProcess函數(shù)聲明做函數(shù)申明。 [DllImport('coredll.Dll', EntryPoint = 'CreateProcess', SetLastError = true)] extern static int CreateProcess(string strImageName, string strCmdLine, IntPtr pProcessAttributes, IntPtr pThreadAttributes, int bInheritsHandle, int dwCreationFlags, IntPtr pEnvironment, IntPtr pCurrentDir, IntPtr bArray, ProcessInfo oProc); public class ProcessInfo { public int hProcess; public int hThread; public int ProcessID; public int ThreadID; } #endregion
方法二:使用Win32 API來實(shí)現(xiàn)外部程序的啟動(dòng)
private void openButton_Click(object sender, EventArgs e) { ProcessInfo pi = new ProcessInfo(); CreateProcess('\\NandFlash\\SerialTST.exe', '', IntPtr.Zero, IntPtr.Zero, 0, 0, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, pi); myprocessID = pi.ProcessID; // 得到該程序的ID } 關(guān)閉外部進(jìn)程的方法就是直接通過獲得的該外部進(jìn)程的ID來關(guān)閉它。這里只介紹使用.Net的Process類的方法: // 關(guān)閉外部進(jìn)程 private void closeButton_Click(object sender, EventArgs e) { Process myProcessA = Process.GetProcessById(myprocessID); // 通過ID關(guān)聯(lián)進(jìn)程 myProcessA.Kill(); // kill進(jìn)程 }
相關(guān)文章
C#實(shí)現(xiàn)的ZPL條碼打印類完整實(shí)例
這篇文章主要介紹了C#實(shí)現(xiàn)的ZPL條碼打印類,結(jié)合實(shí)例形式詳細(xì)分析了C#實(shí)現(xiàn)條碼打印的原理與使用方法,代碼注釋中備有詳盡的說明,便于理解使用,需要的朋友可以參考下2016-06-06C#中實(shí)現(xiàn)輸入漢字獲取其拼音(漢字轉(zhuǎn)拼音)的2種方法
這篇文章主要介紹了C#中實(shí)現(xiàn)輸入漢字獲取其拼音(漢字轉(zhuǎn)拼音)的2種方法,本文分別給出了使用微軟語言包、手動(dòng)編碼實(shí)現(xiàn)兩種實(shí)現(xiàn)方式,需要的朋友可以參考下2015-01-01淺談C#中HttpWebRequest與HttpWebResponse的使用方法
本篇文章主要介紹了淺談C#中HttpWebRequest與HttpWebResponse的使用方法,具有一定的參考價(jià)值,有興趣的可以了解一下。2017-01-01