什么可能阻止NodeMouseClick事件被触发?

时间:2011-01-30 06:37:55

标签: c# .net winforms treeview treenode

我正在使用一个Windows窗体应用程序,我有树视图来显示文件夹列表,并且我附加了NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)事件。 并且在点击节点时我调用服务器方法来填充树视图。 在这里,我可以看到我的一个树节点的NodeMouseClick根本没有被触发。 然而,对于其余的节点,它的工作正常,没有问题。任何人都可以告诉我它没有被触发的确切原因是什么。 我不想使用After_Select事件。

public Form1()
    {
        InitializeComponent();
        Init();
    }

    private void Init()
    {
        treeView1.Nodes.Add("root");

        for (int i = 0; i < 23; i++)
        {
            treeView1.Nodes[0].Nodes.Add(i.ToString());
            treeView1.Nodes[0].Nodes[i].Nodes.Add("child" + i.ToString());
        }

        treeView1.Nodes[0].Expand();
    }

使用大小= 280,369的树视图

2 个答案:

答案 0 :(得分:1)

正如我之前在评论中提到的,解决方法是下拉到Windows API的级别,拦截鼠标消息,并自己引发节点点击事件。代码很难看,但很实用。

将以下代码添加到项目中的新类(我称之为CustomTreeView):

class CustomTreeView : System.Windows.Forms.TreeView
{
    public event EventHandler<TreeNodeMouseClickEventArgs> CustomNodeClick;

    private const int WM_LBUTTONDOWN = 0x201;

    protected override void WndProc(ref System.Windows.Forms.Message m)
    {
        if (m.Msg == WM_LBUTTONDOWN)  // left mouse button down
        {
            // get the current position of the mouse pointer
            Point mousePos = Control.MousePosition;

            // get the node the user clicked on
            TreeNode testNode = GetNodeAt(PointToClient(mousePos));

            // see if the clicked area contained an actual node
            if (testNode != null)
            {
                // A node was clicked, so raise our custom event
                var e = new TreeNodeMouseClickEventArgs(testNode,
                                 MouseButtons.Left, 1, mousePos.X, mousePos.Y);
                if (CustomNodeClick != null)
                    CustomNodeClick(this, e);
            }
        }

        // call through to let the base class process the message
        base.WndProc(ref m);
    }
}

然后将代码中对System.Windows.Forms.TreeView控件的所有引用更改为刚刚创建的新CustomTreeView类。这是您要使用的现有TreeView控件的子类。如果您不熟悉子类化,这是我们修改现有控件的现有功能或新功能的方式。在这种情况下,我们已经对原始TreeView控件进行了子类化,以便在我们检测到用户点击某个节点时添加我们将自己提升的CustomNodeClick事件。

最后,更改表单类中的事件处理程序方法,以侦听我们正在引发的CustomNodeClick事件,而不是之前尝试使用的错误NodeMouseClick事件。

编译并运行。一切都应该按预期工作。

答案 1 :(得分:0)

尝试使用AfterSelect事件必须在选择任何节点后触发它。

相关问题