C# TreeView 自定义显示checkbox
本项目需要对TreeView进行定制,要求比较简单,主要要求如下:
- Winform中TreeView控件默认只支持所有级别的CheckBox显示或者不显示,不能控制制定Level的树节点显示
效果如下:
效果实现代码:
(1)属性和事件设置
this.treeViewGroupStatements.CheckBoxes = true;
this.treeViewGroupStatements.DrawMode = TreeViewDrawMode.OwnerDrawAll;
this.treeViewGroupStatements.DrawNode+=new DrawTreeNodeEventHandler(treeViewGroupStatements_DrawNode);
(2)实现代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
#region 隐藏CheckBoxs //要隐藏的TreeNode的level public ArrayList HideLevelList = new ArrayList() { 0, 1 }; private void treeViewGroupStatements_DrawNode( object sender, DrawTreeNodeEventArgs e) { HideLevelOfTreeView(e.Node); e.DrawDefault = true ; } private void HideLevelOfTreeView(TreeNode tn) { //控制这个条件可以自定义显示checkbox的条件 if (HideLevelList.Contains(tn.Level)) 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 |