我有一个从 UserControl 类继承的自定义控件。它有一个 ToolTip 属性,但是当鼠标拖到它上面时我需要显示它。
Tooltip.Show方法需要 Control 类型的第二个参数。我不知道如何处理它。
任何想法/帮助表示赞赏。
我有一个从 UserControl 类继承的自定义控件。它有一个 ToolTip 属性,但是当鼠标拖到它上面时我需要显示它。
Tooltip.Show方法需要 Control 类型的第二个参数。我不知道如何处理它。
任何想法/帮助表示赞赏。
SetToolTip() 只需调用一次
class Foo : Form {
ToolTip tooltip = new ToolTip();
public Foo(){
tooltip.SetToolTip(this, "This is a tooltip!");
foreach(Control ctrl in this.Controls) {
tooltip.SetToolTip(ctrl, "This is a tooltip!");
}
}
}
在构造函数中实例化您的工具提示并在鼠标悬停事件中显示它。
取自 Joseph 在 stackoverflow 中的回答
public ToolTip tT { get; set; }
public ClassConstructor()
{
tT = new ToolTip();
}
private void MyControl_MouseHover(object sender, EventArgs e)
{
tT.Show("Why So Many Times?", this);
}
希望能帮助到你。
今天自己遇到了这个问题,并想出了这个相当简单的解决方案。
将以下源文件添加到您的代码库中的某处(我将其放在文件 ToolTipEx.cs 中)
namespace System.Windows.Forms
{
public static class ToolTipEx
{
private static void SetTipRecurse(ToolTip toolTip, Control control, string tip)
{
toolTip.SetToolTip(control, tip);
foreach (Control child in control.Controls)
SetTipRecurse(toolTip, child, tip);
}
public static void SetTooltip(this ToolTip toolTip, UserControl control, string tip)
{
SetTipRecurse(toolTip, control, tip);
}
}
}
如果它在另一个 DLL 中,请确保引用了该 DLL。
然后你所要做的就是进行正常的调用,toolTip.SetToolTip(myControl, "some tip");
编译器会为你处理剩下的事情。
因为该函数本质上将 ToolTip.SetToolTip() 方法扩展为具有签名的方法
ToolTip(UserControl control, string tip);
在层次结构中比原来的更高
ToolTip(Control control, string tip);
当我们处理一个 UserControl 时,它将被调用而不是原来的。
新方法执行一个简单的递归调用,为所有子控件提供与父控件相同的工具提示。
此代码假定在调用 SetToolTip 后,UserControl 不会添加其他控件。
我自己也需要这个,发现上面提供的部分解决方案可以改进。
基本上,您需要将所有适用的子控件的 MouseHover 事件设置为父 UserControl 的 MouseHover。
这可以通过 MyUserControl 类构造函数中的以下代码来完成:
class MyUserControl:UserControl
{
string strTooltip;
public ToolTip toolTip
{
get;
set;
}
public MyUserControl()
{
toolTip = new ToolTip();
foreach(Control ctrl in this.Controls)
{
ctrl.MouseHover += new EventHandler(MyUserControl_MouseHover);
ctrl.MouseLeave += new EventHandler(MyUserControl_MouseLeave);
}
}
void MyUserControl_MouseLeave(object sender, EventArgs e)
{
toolTip.Hide(this);
}
void MyUserControl_MouseHover(object sender, EventArgs e)
{
toolTip.Show(strToolTip, this, PointToClient(MousePosition));
}
}
请注意,我们使用 PointToClient(MousePosition) 将工具提示定位到用户控件所在的位置。
否则,有时,它可能会导致工具提示显示在屏幕上的随机位置。希望这对某人有帮助!:)