private static IntPtr GetWindowHandle() { IntPtr hWnd = IntPtr.Zero; var threadId = GetWindowThreadProcessId(GetForegroundWindow(), IntPtr.Zero); var info = new GUITHREADINFO(); info.cbSize = Marshal.SizeOf(info); var success = GetGUIThreadInfo(threadId, ref info); var focusedHandle = GetFocusedHandle(); if (success) { if (info.hwndCaret != IntPtr.Zero) { hWnd = info.hwndCaret; } else if (info.hwndFocus != IntPtr.Zero) { hWnd = info.hwndFocus; } else if (focusedHandle != IntPtr.Zero) { hWnd = focusedHandle; } else if (info.hwndActive != IntPtr.Zero) { hWnd = info.hwndActive; } } else { hWnd = focusedHandle; } if (hWnd == IntPtr.Zero) { hWnd = GetForegroundWindow(); } return(hWnd); }
static extern bool GetGUIThreadInfo(uint idThread, ref GUITHREADINFO lpgui);