許多用戶在程序開發(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)注
關(guān)注
7文章
6101瀏覽量
36301
發(fā)布評(píng)論請(qǐng)先 登錄
DEKRA德凱成為沙特通信和信息技術(shù)設(shè)備技術(shù)法規(guī)認(rèn)證機(jī)構(gòu)
科普|信創(chuàng)是什么?一文讀懂“信息技術(shù)應(yīng)用創(chuàng)新”戰(zhàn)略

施耐德電氣創(chuàng)贏計(jì)劃第六季正式啟動(dòng)
2025第二屆教育信息技術(shù)應(yīng)用創(chuàng)新大賽啟動(dòng),誠邁科技邀您挑戰(zhàn)!

評(píng)論