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.


        [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

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s