Click here to Skip to main content
15,867,756 members
Articles / Desktop Programming / Windows Forms

Control in Focus in Other Processes

Rate me:
Please Sign up or sign in to vote.
4.86/5 (5 votes)
1 Apr 2009CPOL1 min read 55K   1.7K   23   5
Retrieve the hWnd of focused controls in other applications.

FocusedControlInOtherProcess

Introduction

This article will describe how you can retrieve the unique handle of any focusable control in any Windows application by simply focusing it. We will do this through a series of P/Invokes to the Win32 API in user32.dll.

Background

People using the Win32 API function GetFocus may have noticed that it will only return the handle (hWnd) of controls in your own application, and if you try focusing in another process, you will get NULL. This is because GetFocus only returns the window with the keyboard focus for the current thread's message queue. And, since our application is not in the same thread, you will get nothing.

Using the code

To get the currently focused control hWnd in another process, we can attach our thread's message queue to a window in another thread, using the AttachThreadInput function.

This is how it's done:

  1. Use the GetForegroundWindow function to get the window with which the user is currently working.
  2. Use the GetWindowThreadProcessId function to get the ID of both this window and yours.
  3. Use the AttachThreadInput function to temporarily associate your thread's message queue with the thread owning the other window.
  4. Use the GetFocus function to get the hWnd!
  5. Use the AttachThreadInput function again to disconnect from the other thread.
C#
using System.Runtime.InteropServices;

public partial class FormMain : Form
{
    [DllImport("user32.dll")]
    static extern IntPtr GetForegroundWindow();

    [DllImport("user32.dll")]
    static extern IntPtr GetWindowThreadProcessId(IntPtr hWnd, IntPtr ProcessId);

    [DllImport("user32.dll")]
    static extern IntPtr AttachThreadInput(IntPtr idAttach, 
                         IntPtr idAttachTo, bool fAttach);

    [DllImport("user32.dll")]
    static extern IntPtr GetFocus();

    public FormMain()
    {
        InitializeComponent();
    }

    private void timerUpdate_Tick(object sender, EventArgs e)
    {
        labelHandle.Text = "hWnd: " + 
                           FocusedControlInActiveWindow().ToString();
    }

    private IntPtr FocusedControlInActiveWindow()
    {
        IntPtr activeWindowHandle = GetForegroundWindow();

        IntPtr activeWindowThread = 
          GetWindowThreadProcessId(activeWindowHandle, IntPtr.Zero);
        IntPtr thisWindowThread = GetWindowThreadProcessId(this.Handle, IntPtr.Zero);

        AttachThreadInput(activeWindowThread, thisWindowThread, true);
        IntPtr focusedControlHandle = GetFocus();
        AttachThreadInput(activeWindowThread, thisWindowThread, false);

        return focusedControlHandle;
    }
}

Requirements for the code, which can be done with the Visual Studio designer:

  • Add a timer with the name timerUpdate and add the timerUpdate_Tick method to the Tick event. Set Interval to 100 and Enabled to true.
  • Add a Label to the form with the name labelHandle.
  • Set FormMain's TopMost property to true.

History

  • 1.0 (1 April 2009) - Initial release.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Sweden Sweden
André Claesson is a developer that uses his skills both in work and as a hobby. He started to write applications for Windows at the age of 15 and sold his first shareware at 16.
He has helped several companies with software projects and has also been employed by UIQ Technology as a C++ developer for almost 3 years.
He is very fond of using new technologies in his projects and he thinks C# and .NET are exiting alternatives to native code.

Comments and Discussions

 
QuestionCan you get the thread of the in-focus windows control in another process from a class that is not a Windows form? Pin
Member 1589364422-Jan-23 9:31
Member 1589364422-Jan-23 9:31 
QuestionSame info as if using GetGUIThreadInfo? Pin
joepit18-Mar-21 7:42
joepit18-Mar-21 7:42 
PraiseThank you Pin
skarstoker9-Dec-17 22:12
skarstoker9-Dec-17 22:12 
QuestionHow to get the controls(like textbox control) from parent window handle? Pin
Member 1144648725-Sep-15 0:41
Member 1144648725-Sep-15 0:41 
QuestionCan I call it from a console app? Pin
Hana Giat30-Dec-09 5:08
Hana Giat30-Dec-09 5:08 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.