GetFocus (user32)
Last changed: -88.50.17.69

.
Summary

C# Signature:

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

VB Signature:

<DllImport("user32.dll", SetLastError:=True)> _
Private Shared Function GetFocus() As IntPtr
End Function

User-Defined Types:

None.

Notes:

None.

Tips & Tricks:

Method for getting WinForm Control associated with the focused window:

public static Control GetFocusedControl()
{
    Control focusedControl = null;
    // To get hold of the focused control:
    IntPtr focusedHandle = GetFocus();
    if(focusedHandle != IntPtr.Zero)
    {
        // Note that if the focused Control is not a .Net control, then this will return null.
        focusedControl = Control.FromHandle(focusedHandle);
    }
    return focusedControl;
}

Sample Code:

IntPtr ptrFocus = GetFocus();

if (ptrFocus != IntPtr.Zero)

{

  //ptrFocus is the object who has focus

}

Alternative Managed API:

Do you know one? Please contribute it!

public static IntPtr GetFocus() {
    foreach (Form f in Application.OpenForms) {
        if (f.ContainsFocus) return f.Handle;
    }
    return IntPtr.Zero;
}

by Attilio Pavone, 30/06/2010 www.utillyty.eu

Documentation
GetFocus on MSDN