我有3个文本框,如何找出当前选中的文本框(具有焦点)。我无法想出任何东西。
Public Class Form1
Public activeTextBox As TextBox = CType(Me.ActiveControl, TextBox)
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
activeTextBox.Text = activeTextBox.Text & "This is text 1"
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
activeTextBox.Text = activeTextBox.Text & "This is the text 2"
End Sub
End Class
答案 0 :(得分:2)
我假设这是一个Windows窗体应用程序。
此similar question提供了两种可能的建议:
Me.ActiveControl
或者,您可以使用Windows API编写一个方法来获取当前具有焦点的控件的句柄。 WindowsClient.Net上的这个article有一个例子。
但是,只有在调用方法时TextBox仍然具有焦点时,这些选项才有效。
在你的按钮事件处理程序中,你试图找出哪个是最后一个活动的TextBox,以便用它做什么。在这种情况下,Me.ActiveControl
将没有多大用处,因为单击按钮后TextBox控件将立即失去焦点。下面的示例代码显示了如何使用TextBox的Enter和Leave事件来跟踪哪个TextBox是最近活动的。我假设TextBox被称为TextBox1。
Public Class Form1
Public activeTextBox As TextBox
Private Sub TextBox_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.Enter, TextBox2.Enter, TextBox3.Enter
activeTextBox = CType(sender, TextBox)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If (activeTextBox IsNot Nothing) Then
activeTextBox.Text = activeTextBox.Text & "This is text 1"
End If
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
If (activeTextBox IsNot Nothing) Then
activeTextBox.Text = activeTextBox.Text & "This is the text 2"
End If
End Sub
End Class