Mong,
I was having a similar problem in an app and my workaround may or may
not work for you. If you put the thread to sleep for a second during
the TextBox.GotFocus event you'll see that the TreeView hasn't fully
updated when the AfterSelect is fired. The node you click is still
highlighted in gray instead of the dark blue. I'm assuming this is
part of the reason it steals the focus back - to redraw itself.
My method.
I have a generic handler, FocusHandler( ) that handles the GotFocus
event for all the controls that get focus from the TreeView. I set a
form-level boolean (GiveMeBackMyFocus) to true in this Handler.
In the TreeView.GotFocus event, I check this boolean. If it's set to
True, then the TreeView gives control back and sets it to False to
prevent it from firing again.
I track the control that needs focus with a form-level
System.Windows.Forms.Control variable that is set during the
AfterSelect event.
Here's a quick example of how I implemented it:
Public Class Form1
Inherits System.Windows.Forms.Form
#Region " Windows Form Designer generated code "
#End Region
Private textBoxNode As TreeNode
Private listNode As TreeNode
Private otherNode As TreeNode
Private GiveMeBackMyFocus As Boolean
Private controlToFocus As Control
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
textBoxNode = Me.TreeView1.Nodes.Add("TextBox Node")
listNode = Me.TreeView1.Nodes.Add("Listbox Node")
otherNode = Me.TreeView1.Nodes.Add("Other Node")
End Sub
Private Sub TreeView1_AfterSelect(ByVal sender As System.Object,
ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles
TreeView1.AfterSelect
If e.Node Is textBoxNode Then
Me.controlToFocus = Me.TextBox1
ElseIf e.Node Is Me.listNode Then
Me.controlToFocus = Me.ListBox1
Else
Return
End If
Me.ActiveControl = Me.controlToFocus
End Sub
Private Sub FocusHandler(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles TextBox1.GotFocus, ListBox1.GotFocus
Me.GiveMeBackMyFocus = True
End Sub
Private Sub TreeView1_GotFocus(ByVal sender As Object, ByVal e As
System.EventArgs) Handles TreeView1.GotFocus
If Me.GiveMeBackMyFocus Then
Me.controlToFocus.Focus()
Me.GiveMeBackMyFocus = False
End If
End Sub
End Class
John