如何检查vb.net winforms中的焦点TextBox?

我在表单中有多个文本框。我如何知道光标当前是什么文本框? 试着这样做:
If TextBox2.Focus() = True Then
            MessageBox.Show("its in two")
        ElseIf TextBox3.Focus = True Then
            MessageBox.Show("its in three")
        End If
但我认为它不起作用。     
已邀请:
显然,如果您在
Button_Click
中调用代码,它将无法工作,因为当您单击Button时,焦点本身将转到您单击的Button。 你可以做两件事: 为所有TextBox创建一个Focus事件并检查其Sender对象。
Private Sub TextBox_Focus(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox2.Enter, TextBox3.Enter
    Dim currTextBox As TextBox = sender

    If currTextBox.Equals(TextBox2) Then
        MessageBox.Show("it's in two")
    ElseIf currTextBox.Equals(TextBox3) Then
        MessageBox.Show("it's in three")
    End If

End Sub
要么 获取全局字符串变量,并在每个TextBox_Focus事件中设置其值,然后在按钮单击事件中检查字符串值。
 Dim str As String  
 Private Sub TextBox2_Focus(ByVal sender As System.Object, ByVal e As System.EventArgs)  Handles TextBox2.Enter
     str = "two"
 End Sub

 Private Sub TextBox3_Focus(ByVal sender As System.Object, ByVal e As System.EventArgs)  Handles TextBox3.Enter
     str = "three"
 End Sub

 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)  Handles Button1.Click
      MessageBox.Show("it's in " & str)
 End Sub
    
TextBox.Focus实际上将焦点分配给给定的文本框。您正在寻找的是TextBox.Focused。 :) 实际上,所有表单控件都具有Focused属性。     
我知道这已经有了一个公认的答案,但我认为这种方法有点容易,对于那些通过谷歌或其他方式找到这种方法的人来说应该是这里的。
Public focussedTextBox As TextBox
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    For Each control As Control In Me.Controls
        If control.GetType.Equals(GetType(TextBox)) Then
            Dim textBox As TextBox = control
            AddHandler textBox.Enter, Sub() focussedTextBox = textBox
        End If
    Next
End Sub
这样,您就可以随时引用focussedTextBox。您应该确保在执行之前检查是否存在focussedTextBox,但是当应用程序首次加载时不会。你可以这样做:
If Not focussedTextBox Is Nothing Then
    ...
End If
或者,您可以在表单加载时将focussedTextBox设置为您选择的TextBox,方法是设置其值或通过聚焦TextBox。     

要回复问题请先登录注册