Reputation: 1055
I have 3 text-boxes, how do I find out which text-box is currently selected (has focus). I am unable to come up with anything.
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
Upvotes: 1
Views: 8464
Reputation: 1082
I am assuming that this is a Windows Forms application.
This similar question offers two possible suggestions:
Me.ActiveControl
Or, you can write a method using the Windows API to get the handle of the control that currently has the focus. This article on WindowsClient.Net has an example.
However, each of these options will only work if the TextBox still has the focus at the time the method is called.
Within your button event handler, you are trying to find out which was the last active TextBox in order to do something with it. In this situation, Me.ActiveControl
will not be much use because the TextBox control will lose focus as soon as you click on the button. The sample code below shows how you might use the Enter and Leave events of the TextBox to keep track of which TextBox was the most recently active. I have assumed the TextBox is called 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
Upvotes: 3