public static void ActivateWindow(IntPtr handle) { var pid = default(int); var fore = User32PI.GetWindowThreadProcessId(User32PI.GetForegroundWindow(), out pid); var target = User32PI.GetWindowThreadProcessId(handle, out pid); User32PI.AttachThreadInput(target, fore, true); User32PI.SetForegroundWindow(handle); User32PI.AttachThreadInput(target, fore, false); User32PI.SetActiveWindow(handle); }
// ======================================== // field // ======================================== // ======================================== // constructor // ======================================== // ======================================== // property // ======================================== // ======================================== // method // ======================================== /// <summary> /// windowをアクティブにする. /// windowClassName,windowTitleは前方一致,moduleFileNameは後方一致. /// nullを渡すとそれぞれ常に適合. /// </summary> public static void ActivateWindow(string windowClassName, string windowTitle, string moduleFileName) { var targetHWnd = IntPtr.Zero; User32PI.EnumWindows( (hWnd, lParam) => { var bufSize = 2048; var buf = new StringBuilder(bufSize); User32PI.GetClassName(hWnd, buf, buf.Capacity); var className = buf.ToString(); User32PI.GetWindowText(hWnd, buf, buf.Capacity); var title = buf.ToString(); var validClassName = string.IsNullOrEmpty(windowClassName) || (!string.IsNullOrEmpty(className) && className.StartsWith(windowClassName)); var validTitle = string.IsNullOrEmpty(windowTitle) || (!string.IsNullOrEmpty(title) && title.StartsWith(windowTitle)); if (validClassName && validTitle) { if (string.IsNullOrEmpty(moduleFileName)) { targetHWnd = hWnd; return(false); } else { var pid = default(int); User32PI.GetWindowThreadProcessId(hWnd, out pid); var process = Process.GetProcessById(pid); var fileName = process.MainModule.FileName; if (!string.IsNullOrEmpty(fileName) && fileName.EndsWith(moduleFileName)) { targetHWnd = hWnd; return(false); } } } return(true); }, IntPtr.Zero ); if (targetHWnd != IntPtr.Zero) { RestoreWindow(targetHWnd); } }