C#: How to avoid TreeNode check from happening on a double click event

こ雲淡風輕ζ 提交于 2019-11-30 08:27:21

This is a bug in the TreeView I think (http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/9d717ce0-ec6b-4758-a357-6bb55591f956/). You need to subclass the tree view and disable the double-click message in order to fix it. Like this:

public class NoClickTree : TreeView
    {
        protected override void WndProc(ref Message m)
        {
            // Suppress WM_LBUTTONDBLCLK
            if (m.Msg == 0x203) { m.Result = IntPtr.Zero; }
            else base.WndProc(ref m);
        }              
    };

Of course if you do this you'll no longer be able to use the double-click metaphor in the tree-view for other things (such as double click a node to launch a property page, or something).

If you want your double click to actually toggle the check box then try:

protected override void WndProc(ref Message m)
{
  // Filter WM_LBUTTONDBLCLK when we're showing check boxes
  if (m.Msg == 0x203 && CheckBoxes)
  {
    // See if we're over the checkbox. If so then we'll handle the toggling of it ourselves.
    int x = m.LParam.ToInt32() & 0xffff;
    int y = (m.LParam.ToInt32() >> 16) & 0xffff;
    TreeViewHitTestInfo hitTestInfo = HitTest(x, y);

    if (hitTestInfo.Node != null && hitTestInfo.Location == TreeViewHitTestLocations.StateImage)
    {
      OnBeforeCheck(new TreeViewCancelEventArgs(hitTestInfo.Node, false, TreeViewAction.ByMouse));
      hitTestInfo.Node.Checked = !hitTestInfo.Node.Checked;
      OnAfterCheck(new TreeViewEventArgs(hitTestInfo.Node, TreeViewAction.ByMouse));
      m.Result = IntPtr.Zero;
      return;
    }
  }

  base.WndProc(ref m);
}
Mikal

I managed it with the following code, which prevents checking root nodes:

private void MyTreeView_MouseUp(object sender, MouseEventArgs e)
{
    // HACK: avoid to check root nodes (mr)
    var node = ((TreeView)sender).GetNodeAt(new Point(e.X, e.Y));
    if (node != null && node.Parent == null)
    BeginInvoke(new MouseEventHandler(TreeView_MouseUpAsync), sender, e);
}

private void TreeView_MouseUpAsync(object sender, MouseEventArgs e)
{
    if (IsDisposed)
        return;

    var node = ((TreeView)sender).GetNodeAt(new Point(e.X, e.Y));
    node.Checked = false;
}

Try extending the TreeNode class and add a boolean property that maintains the proper checkedState. That way, when someone double-clicks a node, you can reset the node's checked state back to the value stored in the property. There might be a more elegant solution, but this is the best I can think of.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!