blez's : blog

code / design / music and more

Get the currently focused control

Leave a comment

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.

        private static extern IntPtr GetForegroundWindow();

        static extern uint GetWindowThreadProcessId(IntPtr hWnd, IntPtr ProcessId);

        static extern uint GetCurrentThreadId();

        static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool fAttach);

        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;

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s