How to get the focus of a text box that is anywhere (such as: on a SplitContainer or any control that contains other controls)

Mansour_Dalir 1,996 Reputation points
2024-11-29T05:43:40.42+00:00

20241129_085319

Private Sub ToolStripButton1_Click(sender As Object, e As EventArgs) Handles ToolStripButton1.Click
		ActiveControl.Text += "A"
	End Sub

VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,760 questions
0 comments No comments
{count} votes

Accepted answer
  1. Jiachen Li-MSFT 32,961 Reputation points Microsoft Vendor
    2024-11-29T06:30:29.69+00:00

    Hi @Mansour_Dalir ,

    You should check the type of the ActiveControl before modifying its text.

    If the ActiveControl is a ContainerControl (like a SplitContainer, TabControl, or Panel), use a helper function to retrieve the actual focused child control.

        Private Sub ToolStripButton1_Click(sender As Object, e As EventArgs) Handles ToolStripButton1.Click
            If TypeOf Me.ActiveControl Is TextBox Then
                Dim activeTextBox As TextBox = CType(Me.ActiveControl, TextBox)
                activeTextBox.Text += "A"
            ElseIf TypeOf Me.ActiveControl Is ContainerControl Then
                Dim focusedControl As Control = GetFocusedControl(Me.ActiveControl)
                If TypeOf focusedControl Is TextBox Then
                    Dim activeTextBox As TextBox = CType(focusedControl, TextBox)
                    activeTextBox.Text += "A"
                End If
            End If
        End Sub
        Private Function GetFocusedControl(container As Control) As Control
            Dim activeControl As Control = container
            While TypeOf activeControl Is ContainerControl AndAlso CType(activeControl, ContainerControl).ActiveControl IsNot Nothing
                activeControl = CType(activeControl, ContainerControl).ActiveControl
            End While
            Return activeControl
        End Function
    
    

    Best Regards.

    Jiachen Li


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.