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

前端 未结 7 1178
逝去的感伤
逝去的感伤 2020-12-03 21:06

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

相关标签:
7条回答
  • 2020-12-03 21:18

    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
    
    0 讨论(0)
  • 2020-12-03 21:19

    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
    
    0 讨论(0)
  • 2020-12-03 21:24

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

    0 讨论(0)
  • 2020-12-03 21:30

    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

    0 讨论(0)
  • 2020-12-03 21:33

    Form.ActiveControl may be what you want.

    0 讨论(0)
  • 2020-12-03 21:35

    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
    
    0 讨论(0)
提交回复
热议问题