Windows 窗体 c# - TreeView:单击树外部时取消选择项目

nlk*_*git 3 c# windows-forms-designer winforms

我有一个树视图,有几个节点。如果我单击树外部,我希望取消选择当前选定的节点。但我找不到要触发的事件,如果我单击空白处,当前选定的节点仍保持选定状态

TaW*_*TaW 6

由于某种原因,<citation needed> MouseClick单击控件的空白部分时将不起作用TreeView。但MouseDown确实:

private void treeView1_MouseDown(object sender, MouseEventArgs e)
{
    var hit = treeView1.HitTest(e.X, e.Y);

    if (hit.Node == null)
    {
        treeView1.SelectedNode = null;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您还想在TreeView丢失时取消选择Focus,您可以编写一个合适的事件:

private void treeView1_Leave(object sender, EventArgs e)
{
    treeView1.SelectedNode = null;
} 
Run Code Online (Sandbox Code Playgroud)

更新

根据MSDN GotFocusLostFocus应避免EnterLeave事件:

GotFocus 和 LostFocus 事件是与 WM_KILLFOCUS 和 WM_SETFOCUS Windows 消息相关的低级焦点事件。通常,GotFocus 和 LostFocus 事件仅在更新 UICues 或编写自定义控件时使用。相反,Enter 和 Leave 事件应该用于除 Form 类之外的所有控件,Form 类使用 Activated 和 Deactivate 事件。有关 GotFocus 和 LostFocus 事件的详细信息,请参阅 WM_KILLFOCUS 和 WM_KILLFOCUS 主题。

请注意,默认情况下HideSelection处于打开状态,因此当TreeView失去焦点时,选择将被隐藏,但仍然有效。