在進行winform開發過程中有時候會需要關閉其他程序或者關閉進程,以前寫過一篇相關介紹的文章,今天有同事問起來,于是在次翻出來和大家分享一下。
下面介紹我所知的兩種方法,應該對大家有幫助,如果有朋友知道其他的方法,謝謝共享一下。
方法1
ProcName 需要關閉的進程名稱
private bool closeProc(string ProcName){ bool result = false; System.Collections.ArrayList procList = new System.Collections.ArrayList(); string tempName = ""; foreach (System.Diagnostics.Process thisProc in System.Diagnostics.Process.GetProcesses()) { tempName = thisProc.ProcessName; procList.Add(tempName); if (tempName == ProcName) { if (!thisProc.CloseMainWindow()) thisProc.Kill(); //當發送關閉窗口命令無效時強行結束進程 result = true; } } return result;}
上面程序里定義了一個ArrayList,當不知道所要關閉的進程的具體名稱的時候,可以將ArrayList 中的值放到一個listbox或其他的控件里面用來選擇進程進行結束。
方法2
在類體中的最上方聲明:
[DllImport("user32.dll", CharSet=CharSet.Auto)] public static extern int SendMessage(int hWnd, int msg, int wParam, int lparam); //SendMessage(hwnd1,WM_CLOSE,0,0); //hwnd1是你用findwindow函數返回的句柄值 //wm_close定義在winuser.h里面 //0x0010是 WM_CLOSE的值 SendMessage(hwnd1,0x0010,0,0);
新聞熱點
疑難解答