在Winform中为TreeView控件增加鼠标旋停时提示节点信息

类别:.NET开发 点击:0 评论:0 推荐:

新建一个WindowsApplication项目,命名为WinTreeViewTip,打开窗体Form1,将TreeView控件拖到界面中,名为treeView1
双击Form1进入后台代码页
首先加入一个ToolTip对象,命名为nodeTip:
private ToolTip nodeTip = null;
然后在Form1的构造函数中进行初始化设置:

this.nodeTip = new System.Windows.Forms.ToolTip();

this.nodeTip.InitialDelay = 300;

this.nodeTip.ReshowDelay = 0;
//为测试添加节点
treeView1.Nodes.Add(new TreeNode("test1"));
treeView1.Nodes.Add(new TreeNode("test2"));
treeView1.Nodes.Add(new TreeNode("test3"));
treeView1.Nodes.Add(new TreeNode("test4"));

在InitializeComponent方法中为treeView1添加MouseMove和MouseLeave事件:
// treeView1
this.treeView1.MouseMove += new System.Windows.Forms.MouseEventHandler(this.treeView1_MouseMove);
this.treeView1.MouseLeave += new System.EventHandler(this.treeView1_MouseLeave);

在treeView1_MouseLeave和treeView1_MouseMove添加如下代码:
private void treeView1_MouseLeave(object sender, System.EventArgs e) {
 nodeTip.Active = true;
}

private void treeView1_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e) {
 TreeNode node = treeView1.GetNodeAt(e.X,e.Y);
 if(node == null){
  nodeTip.Active = false;
 }
 else{
  nodeTip.SetToolTip((TreeView)sender,node.Text);
  nodeTip.Active = true;
 }
}

本文地址:http://com.8s8s.com/it/it41949.htm