当用户将鼠标悬停在TreeView控件的特定TreeNode控件上时,显示不同的光标



当用户将指针悬停在具有特定命名父节点的节点上时,我要求表单的光标更改为光标Cursors.Hand

我在实现这一点时遇到的问题是,当用户将指针从所关注的TreeNode移开时,将光标改回默认光标。

我已经处理了TreeView控件的NodeMouseHover事件(如最后的代码片段中所示(,以在指针移动到另一个节点时将指针更改为备用光标并返回默认光标,但这不处理用户将指针从节点移动到TreeView控件的空白区域时的情况。

关于这个问题的解决方案,我最初也是唯一的直觉是获得TreeNode的位置并计算需要光标更改的区域,并检查指针是否仍在TreeView控件的MouseMove事件的事件处理程序上的其中一个上,但是,我相信,这不是一个优雅的解决方案,因为有很多TreeNode需要这种行为,这将需要循环通过其中的许多进行检查,这反过来可能会导致应用程序在极少数情况下有点不响应。

提前谢谢。

PS有问题的代码片段:

this.treeView.NodeMouseHover += delegate (object sender, TreeNodeMouseHoverEventArgs e)
{
bool isNewCursorAssigned = false;
if (e.Node.Parent != null)
{
if (e.Node.Parent.Text == "someTxt")
{
this.Cursor = Cursors.Hand;
isNewCursorAssigned = true;
}
}
if (isNewCursorAssigned == false && this.Cursor != this.DefaultCursor)
this.Cursor = this.DefaultCursor;
};

改为处理MouseMove,从当前鼠标位置获取Node,向后迭代以获取当前NodeParent(以及父级的父级,如果有(,并相应地更改Cursor

private void treeView1_MouseMove(object sender, MouseEventArgs e)
{
var node = treeView1.GetNodeAt(e.Location);
if (node != null)
{
var parent = node.Parent;
while (parent != null)
{
if (parent.Text == "someTxt")
{
if (Cursor != Cursors.Hand)
Cursor = Cursors.Hand;
return;
}
parent = parent.Parent;
}
Cursor = Cursors.Default;
}
}

还要处理MouseLeave事件,以检查是否需要默认Cursor

private void treeView1_MouseLeave(object sender, EventArgs e)
{
if (Cursor != Cursors.Default)
Cursor = Cursors.Default;
}

或者,如果您更喜欢Lambda方式:

//In the constructor:
treeView1.MouseMove += (s, e) =>
{
var node = treeView1.GetNodeAt(e.Location);
if (node != null)
{
var parent = node.Parent;
while (parent != null)
{
if (parent.Text == "someTxt")
{
if (Cursor != Cursors.Hand)
Cursor = Cursors.Hand;
return;
}
parent = parent.Parent;
}
Cursor = Cursors.Default;
}
};
treeView1.MouseLeave += (s, e) =>
{
if (Cursor != Cursors.Default)
Cursor = Cursors.Default;
};

当光标横向移动超过节点文本的边界时,我认为必须这样做才能合并光标更改。

this.treeView.MouseMove += delegate (object sender, MouseEventArgs e)
{
TreeNode concernedNode = this.treeViewOfAvailableMachines.GetNodeAt(e.Location);
if (concernedNode != null)
if (!(concernedNode.Parent != null && concernedNode.Parent.Text == "someTxt"))
concernedNode = null;
if (concernedNode != null)
{
if ((e.Location.X >= concernedNode.Bounds.Location.X &&
e.Location.X <= concernedNode.Bounds.Location.X + concernedNode.Bounds.Width) &&
(e.Location.Y >= concernedNode.Bounds.Location.Y &&
e.Location.Y <= concernedNode.Bounds.Location.Y + concernedNode.Bounds.Height))
{
this.Cursor = Cursors.Hand;
}
else
{
this.Cursor = this.DefaultCursor;
}
}
else
{
this.Cursor = this.DefaultCursor;
}
};

最新更新