It’s easy to get the currently foreground window (using the GetForegroundWindow API), but what about the currently focused child window?
Here’s one way.
[DllImport("user32.dll")] private static extern IntPtr GetForegroundWindow(); [DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr hWnd, IntPtr ProcessId); [DllImport("kernel32.dll")] static extern uint GetCurrentThreadId(); [DllImport("user32.dll")] static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool fAttach); [DllImport("user32.dll")] static extern IntPtr GetFocus(); [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount); public static IntPtr GetCurrentFocusWindow() { var remoteThreadId = GetWindowThreadProcessId(GetForegroundWindow(), IntPtr.Zero); var currentThreadId = GetCurrentThreadId(); // AttachThreadInput is needed so we can get the handle of a focused window in another app AttachThreadInput(remoteThreadId, currentThreadId, true); // Get the handle of a focused window IntPtr focussed = GetFocus(); // Now detach since we got the focused handle AttachThreadInput(remoteThreadId, currentThreadId, false); return focussed; }
Advertisements