如何在MouseView和Key事件上确定TreeView上的节点

时间:2017-10-17 19:56:11

标签: c# .net winforms treeview

我有System.Windows.Forms.TreeView。用户可以使用鼠标或键盘进行导航。我有两个事件处理程序。 鼠标单击事件运行良好,但我遇到的问题是KeyEventArg不知道树中的节点(TreeNodeMouseClickEventArgs也是如此)。 那么当使用向上和向下键时,代码如何知道用户在TreeView中的位置?

MyView.Designer.cs

this.trvApproval.NodeMouseClick += new System.Windows.Forms.TreeNodeMouseClickEventHandler(this.trvApproval_NodeMouseClick);
this.trvApproval.KeyUp += new System.Windows.Forms.KeyEventHandler(this.trvApproval_KeyUp);

MyView.cs

private void trvApproval_NodeMouseClick(object sender, System.Windows.Forms.TreeNodeMouseClickEventArgs eventArgs)
{
    this.trvApproval.SelectedNode = eventArgs.Node;
}

private void trvApproval_KeyUp(object sender, System.Windows.Forms.KeyEventArgs eventArgs)
{
    // No knowledge of tree in KeyEventArgs
    if (eventArgs.KeyValue == Convert.ToChar(Keys.Down))
    {
        System.Diagnostics.Trace.WriteLine("trvApproval_KeyPress Down: " + eventArgs.KeyValue);
    }
    else if (eventArgs.KeyValue == Convert.ToChar(Keys.Up))
    {
        System.Diagnostics.Trace.WriteLine("trvApproval_KeyPress Up: " + eventArgs.KeyValue);
    }
}

1 个答案:

答案 0 :(得分:1)

您无需处理键盘或鼠标事件,只需处理TreeView e.Node控制事件。使用鼠标或键盘选择节点时,事件将会提升。 private void treeView1_AfterSelect(object sender, TreeViewEventArgs e) { //e.Node is what you are looking for. } 是您要查找的节点:

count