C# – Windows Forms TreeView always selects a node on focus

ctreeviewwinforms

The TreeView in Windows Forms always seems to want a node selected when it regains focus. If I have no nodes selected, and that treeview gains focus, I'll get an AfterSelect event with the first node selected, even though I didn't select it using the keyboard, mouse, or programmatically. The only workaround I can find is to check if the TreeViewCancelEventArgs.Action equals TreeViewAction.Unknown and then canceling the selection. This seems really hacky, so I'm wondering if there's another way to fix this.

Best Answer

I agree that using TreeViewAction.Unknown in this case is less than desirable. Consider using the BeforeSelect event, which provides an opportunity to prevent the AfterSelect event.

Create a GotFocus event handler that sets a flag. Then, create a BeforeSelect event handler that, if the flag is set, cancels the event and clears the flag. For example:

private bool treeViewWasNewlyFocused = false;

private void TreeView1_BeforeSelect(object sender, TreeViewCancelEventArgs e)
{
    if(treeViewWasNewlyFocused)
    {
        e.Cancel = true;
        treeViewWasNewlyFocused = false;
    }
}

private void TreeView1_GotFocus(object sender, EventArgs e)
{
    treeViewWasNewlyFocused = true;
}
Related Topic