How do I find out which control has focus in Windows Forms?
You can use this to find by Control Name .
If DataGridView1.Name = Me.ActiveControl.Name Then
TextBox1.Visible = True
Else
TextBox1.Visible = False
End If
Note that a single call to ActiveControl is not enough when hierarchies are used. Imagine:
Form
TableLayoutPanel
FlowLayoutPanel
TextBox (focused)
(formInstance).ActiveControl
will return reference to TableLayoutPanel
, not the TextBox
So use this (full disclosure: adapted from this C# answer)
Function FindFocussedControl(ByVal ctr As Control) As Control
Dim container As ContainerControl = TryCast(ctr, ContainerControl)
Do While (container IsNot Nothing)
ctr = container.ActiveControl
container = TryCast(ctr, ContainerControl)
Loop
Return ctr
End Function
Something along these lines:
Protected Function GetFocusControl() As Control
Dim focusControl As Control = Nothing
' Use this to get the Focused Control:
Dim focusHandle As IntPtr = GetFocus()
If IntPtr.Zero.Equals(focusHandle) Then
focusControl = Control.FromHandle(focusHandle)
End If
' Note that it returns NOTHING if there is not a .NET control with focus
Return focusControl
End Function
I think this code came from windowsclient.net, but it's been a while so...
I used following:
Private bFocus = False
Private Sub txtUrl_MouseEnter(sender As Object, e As EventArgs) Handles txtUrl.MouseEnter
If Me.ActiveControl.Name <> txtUrl.Name Then
bFocus = True
End If
End Sub
Private Sub txtUrl_MouseUp(sender As Object, e As MouseEventArgs) Handles txtUrl.MouseUp
If bFocus Then
bFocus = False
txtUrl.SelectAll()
End If
End Sub
I set the Variable only on MouseEnter to improve the magic
Form.ActiveControl may be what you want.
In C# I do this:
if (txtModelPN != this.ActiveControl)
txtModelPN.BackColor = Color.White;
txtModelPN is a textbox that I am highlighting on enter and mouseEnter and de-highlighting on Leave,MouseLeave. Except if it is the current control I don't set the background back to white.
The VB equivalent would be like this
IF txtModelPN <> Me.ActiveControl Then
txtModelPN.BackColor = Color.White
End If