摘要:Process.MainWindowHandle無法獲取已最小化的窗口的句柄,可以用FindWindow傳入窗口標題文字來獲取窗口句柄
我最近做一個軟件,需要只有一個進程運行,並且第二次點擊程序后,要顯示之前運行程序的窗口,再關掉當前進程。
不過在使用Process.MainWindowHandle獲取主窗體句柄時,發現無法獲取已最小化窗體的句柄
網上找了點資料,發現可以通過WindowsAPI來獲取。
思路如下
1.使用Process.GetProcessesByName() 獲取已運行的程序進程
2.和當前進程對比,如果id不同,即為之前已開啟的程序
3.獲取已開啟進程的MainWindowHandle,如果為0,則使用FindWindow獲取窗口句柄,並用GetWindowThreadProcessId函數來驗證句柄屬否屬於該進程
下面是代碼
/// <summary> /// 根據窗口標題查找窗體 /// </summary> /// <param name="lpClassName"></param> /// <param name="lpWindowName"></param> /// <returns></returns> [System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint = "FindWindow")] private static extern IntPtr FindWindow(string lpClassName, string lpWindowName); /// <summary> /// 根據句柄查找進程ID /// </summary> /// <param name="hwnd"></param> /// <param name="ID"></param> /// <returns></returns> [System.Runtime.InteropServices.DllImport("User32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)] public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID); /// <summary> /// 打開該程序主窗口 /// </summary> public static void RaiseOtherProcess() { System.Diagnostics.Process proc = System.Diagnostics.Process.GetCurrentProcess(); Process[] Proes = System.Diagnostics.Process.GetProcessesByName(proc.ProcessName); foreach (System.Diagnostics.Process otherProc in Proes) { if (proc.Id != otherProc.Id) { IntPtr hWnd = otherProc.MainWindowHandle; if (hWnd.ToInt32() == 0) { hWnd = FindWindow(null, "程序主窗口標題"); int id = -1; GetWindowThreadProcessId(hWnd, out id); if (id == otherProc.Id) break; }
//此處獲取的hWnd即為之前運行程序的主窗口句柄,再使用其他函數打開窗體 break; } } }