WinForm中TreeView中部分节点前面的CheckBox隐藏
在Winform中需要想实现TreeView树中部分节点前面的CheckBox隐藏,Winform并没有提供相应的属性来隐藏节点的CheckBox,需要用户重绘节点。
项目截图:
一下就是一个全代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace TreeViewDemoWindowsFormsApp2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
this.treeView1.ExpandAll();
this.treeView1.DrawMode = TreeViewDrawMode.OwnerDrawAll;
this.treeView1.DrawNode += new DrawTreeNodeEventHandler(tvCheck_DrawNode);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
private void tvCheck_DrawNode(object sender, DrawTreeNodeEventArgs e)
{
try
{
if (e.Node.Text == "节点7" || e.Node.Text == "节点6")
{
HideCheckBox(this.treeView1, e.Node);
}
e.DrawDefault = true;
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
try
{
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
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)
{
try
{
TVITEM tvi = new TVITEM();
tvi.hltem = node.Handle;
tvi.mask = TVIF_STATE;
tvi.stateMask = TVIS_STATEIMAGEMASK;
tvi.state = 0;
SendMessage(tvw.Handle, TVM_SETITEM, IntPtr.Zero, ref tvi);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
[StructLayout(LayoutKind.Sequential, Pack = 8, CharSet = CharSet.Auto)]
private struct TVITEM
{
public int mask;
public IntPtr hltem;
public int state;
public int stateMask;
[MarshalAs(UnmanagedType.LPTStr)]
public string IpszText;
public int cchTextMax;
public int iImage;
public int iSelectedImange;
public int cChildren;
public IntPtr IParam;
}
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, ref TVITEM Iparam);
}
}
项目地址:https://download.csdn.net/download/xwwwill/87789489