Live Chat Icon For mobile
Live Chat Icon

How do I get hold of the currently focused Control?

Platform: WinForms| Category: Controls

The .Net framework libraries does not provide you an API to query for the focused Control. You have to invoke a windows API to do so:


[C#]
public class MyForm : Form
{
		[DllImport('user32.dll', CharSet=CharSet.Auto, CallingConvention=CallingConvention.Winapi)] 
		internal static extern IntPtr GetFocus();

		private 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;
		}
}

[VB.Net]
Public Class Form1

’ Declare the GetFocused method here:
     _
    Public Shared Function GetFocus() As IntPtr
    End Function


    Private Function GetFocusedControl() As Control
        Dim focusedControl As Control = Nothing
        ’ To get hold of the focused control:
        Dim focusedHandle As IntPtr = GetFocus()
        If IntPtr.Zero.Equals(focusedHandle) Then
            ’ Note that if the focused Control is not a .Net control, then this will return null.
            focusedControl = Control.FromHandle(focusedHandle)
        End If
        Return focusedControl
    End Function

End Class

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.