How to determine which control on form has focus?

后端 未结 4 653
轻奢々
轻奢々 2021-01-11 10:20

I\'ve read elsewhere on here that to capture \"Enter\" key stroke in a text box and use it as if pushing a button I should set the KeyPreview property of the form to true an

4条回答
  •  悲&欢浪女
    2021-01-11 10:57

    You could use this code as a starting point to capture the key down events of the form. The ActiveControl is one that has the focus. In this example, it's flexible for adding other actions on "Enter" when you are in different TextBoxes on the form. It's VB.NET, but you should be able to easily convert to C#.

    Private Sub MyForm_KeyDown(ByVal sender As Object, _
        ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
    
        If e.KeyCode = Keys.Enter Then
            If Me.ActiveControl.Name = Me.TextBox1.Name Then
                ' This is the TextBox we want to be active to run filterByDeviceSN()
                filterByDeviceSN()
            ElseIf Me.ActiveControl.Name = Me.TextBox2.Name Then
                foo()
            End If
        End If
    End Sub
    

提交回复
热议问题