Windows窗体:TreeView控件在鼠标左键和右键单击后的响应不同

3

我在Windows窗体中有一个树形视图(TreeView)。当我左键单击树形视图中的节点时,e.Node 显示正确的值,但是当我右键单击同一节点时,在AfterSelect事件中,e.Node显示父节点的值。可能的原因是什么?我该如何在右键单击时仍然获取实际的节点?

 private void trView_AfterSelect(object sender, TreeViewEventArgs e)
 {    
     //e.Node is parent Node at Right click
     //e.Node is correct node at Left Click
        if (e.Node.IsSelected)
        {


        }
 }

1个回答

2
链接的文章介绍了如何使用 MouseDown 选择节点。但是你需要知道,当你单击 TreeView 中的 +/- 时,MouseDown 事件也会触发,而你希望让 +/- 执行其原始操作。因此,通常需要检查其他一些条件,以避免在 TreeView 中出现不必要的行为:
  • 您可以通过检查 TreeViewHitTest 方法的结果来判断鼠标是否没有落在 +/- 上。

  • 您可以通过检查事件参数的 Button 属性,判断鼠标点击事件是否由右键触发。

示例

private void treeView1_MouseDown(object sender, MouseEventArgs e)
{
    TreeNode node = null;
    node = treeView1.GetNodeAt(e.X, e.Y);
    var hti = treeView1.HitTest(e.Location);

    if (e.Button != MouseButtons.Right ||
        hti.Location == TreeViewHitTestLocations.PlusMinus ||
        node == null)
    {
        return;
    }
    treeView1.SelectedNode = node;
    contextMenuStrip1.Show(treeView1, node.Bounds.Left, node.Bounds.Bottom);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接