C# 的TreeView的checkbox有个存在很久的bug,双击会改变checkbox状态但不触发AfterCheck和BeforeCheck,导致和子级联动时会有问题。

https://download.csdn.net/download/tokyo2008/4636514下载的解决方法可以屏蔽在checkbox上的双击,但是快速点击鼠标时的反应让我很难受,我作出了一个改进。

这是原版:

public class TreeViewEx : TreeView
    {
        private const int WM_LBUTTONDBLCLK = 0x0203;
        private const int WM_RBUTTONDOWN = 0x0204;
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == WM_LBUTTONDBLCLK)
            {
                TreeViewHitTestInfo tvhti = HitTest(new Point((int)m.LParam));
                if (tvhti != null && tvhti.Location == TreeViewHitTestLocations.StateImage)
                {
                    m.Result = IntPtr.Zero;
                    return;
                }
            }
            else if (m.Msg == WM_RBUTTONDOWN)
            {
                TreeViewHitTestInfo tvhti = HitTest(new Point((int)m.LParam));
                if (tvhti != null)
                    this.SelectedNode = tvhti.Node;
            }
            base.WndProc(ref m);
        }
    }

这是我改进的:

public class TreeViewEx : TreeView
    {
        private const int WM_LBUTTONDBLCLK = 0x0203;
        private const int WM_RBUTTONDOWN = 0x0204;
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == WM_LBUTTONDBLCLK)
            {
                TreeViewHitTestInfo tvhti = HitTest(new Point((int)m.LParam));
                if (tvhti != null && tvhti.Location == TreeViewHitTestLocations.StateImage)
                {
                    m.Result = IntPtr.Zero;
                    tvhti.Node.Checked = !tvhti.Node.Checked;
                    return;
                }
            }
            else if (m.Msg == WM_RBUTTONDOWN)
            {
                TreeViewHitTestInfo tvhti = HitTest(new Point((int)m.LParam));
                if (tvhti != null)
                    this.SelectedNode = tvhti.Node;
            }
            base.WndProc(ref m);
        }
    }

这样可以使checkbox做出和没屏蔽时一样的反应,不同的是这样可以触发AfterCheck事件。

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐