The .NET Framework Class Library does not provide a method to determine which control has keyboard focus, but you can invoke a Win32 API function to do this.
Here's a custom form class that adds a GetFocusControl method to retrieve the .NET control that has the keyboard focus. If the window that has the focus is not a .NET control, the method returns null (Nothing in VB).
[C#]
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
public class FormWithGetFocusControl : Form
{
// Import GetFocus() from user32.dll
[ DllImport( "user32.dll", CharSet=CharSet.Auto,
CallingConvention=CallingConvention.Winapi ) ]
internal static extern IntPtr GetFocus();
protected Control GetFocusControl()
{
Control focusControl = null;
IntPtr focusHandle = GetFocus();
if ( focusHandle != IntPtr.Zero )
// returns null if handle is not to a .NET control
focusControl = Control.FromHandle( focusHandle );
return focusControl;
}
}
[Visual Basic]
Public Class FormWithGetFocusControl
Inherits Form
' Import GetFocus() from user32.dll
Public Shared Function GetFocus() As IntPtr
End Function
Protected Function GetFocusControl() As Control
Dim focusControl As Control = Nothing
' To get hold of the focused control:
Dim focusHandle As IntPtr = GetFocus()
If IntPtr.Zero.Equals(focusHandle) Then
' returns Nothing if handle is not to a .NET control
focusControl = Control.FromHandle(focusHandle)
End If
Return focusControl
End Function
End Class
Contributed from George Shepherd's Windows Forms FAQ