How do I find out which control has focus in .NET

2019-01-12 06:10发布

问题:

How do I find out which control has focus in Windows Forms?

回答1:

Form.ActiveControl may be what you want.



回答2:

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


回答3:

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


回答4:

You can use the ActiveControl propert of the form and can use that control.

me.ActiveControl

Or

Form.ActiveControl


回答5:

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


回答6:

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



回答7:

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...