TreeView隐藏指定节点的CheckBox

因为TreeView 自身的CheckBox非常死,开启后所有的节点都会显示,但是很多场景下顶级节点是不需要显示CheckBox的,被迫通过重绘和SendMessage来解决这个问题。

this.treeView1.CheckBoxes = true;
this.treeView1.DrawMode = TreeViewDrawMode.OwnerDrawAll;
this.treeView1.DrawNode += new DrawTreeNodeEventHandler(treeViewGroupStatements_DrawNode);//注册事件
#region 隐藏CheckBoxs

        //要隐藏的TreeNode的字典
        public Dictionary<string, bool> HideList = new Dictionary<string, bool>(); 
        private void treeViewGroupStatements_DrawNode(object sender, DrawTreeNodeEventArgs e)
        {
            HideLevelOfTreeView(e.Node);
            e.DrawDefault = true;

        }
        private void HideLevelOfTreeView(TreeNode tn)
        {
            //控制这个条件可以自定义显示checkbox的条件
            if (HideList.ContainsKey(tn.Text))
                HideCheckBox(tn.TreeView, tn);
        }

        //#endregion


        private const int TVIF_STATE = 0x8;
        private const int TVIS_STATEIMAGEMASK = 0xF000;
        private const int TV_FIRST = 0x1100;
        private const int TVM_SETITEM = TV_FIRST + 63;
        private void HideCheckBox(TreeView tvw, TreeNode node)
        {

            TVITEM tvi = new TVITEM();

            tvi.hItem = node.Handle;

            tvi.mask = TVIF_STATE;

            tvi.stateMask = TVIS_STATEIMAGEMASK;

            tvi.state = 0;

            SendMessage(tvw.Handle, TVM_SETITEM, IntPtr.Zero, ref tvi);

        }

        [StructLayout(LayoutKind.Sequential, Pack = 8, CharSet = CharSet.Auto)]

        private struct TVITEM
        {
            public int mask;
            public IntPtr hItem;
            public int state;
            public int stateMask;
            [MarshalAs(UnmanagedType.LPTStr)]
            public string lpszText;
            public int cchTextMax;
            public int iImage;
            public int iSelectedImage; public int cChildren; public IntPtr lParam;
        }

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        private static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, ref TVITEM lParam);
        #endregion

 

posted @ 2018-05-17 15:45  clown  阅读(1661)  评论(0编辑  收藏  举报