November 15, 2005

GotFocus()?

I always have to look for this code, so i'm posting it here so i know where it is :)

from http://www.syncfusion.com/FAQ/WindowsForms/FAQ_c41c.aspx#q1021q

jk

----------------------------------------------------
How do I get hold of the currently focused Control?

The .Net framework libraries do 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();

// Note that if the focused Control is not a .Net control,
//then this will return null.
if(focusedHandle != IntPtr.Zero)
focusedControl = Control.FromHandle(focusedHandle);

return focusedControl;
}
}