鼠标悬停时,工具提示显示多次

5

我有一个自定义控件(C#,Visual Studio)。我想在鼠标悬停事件中显示工具提示。

然而,无论我做什么,它要么从未显示,要么有多次显示的机会。

我认为这应该很简单:

private void MyControl_MouseHover(object sender, EventArgs e)
{
    ToolTip tT = new ToolTip();

    tT.Show("Why So Many Times?", this);
}

但这并不起作用。我已经尝试了很多方法,但似乎无法使其正常工作。我希望将工具提示作为组件的一部分,因为我想访问其中的私有字段以进行显示。
感谢任何帮助。
4个回答

10

你尝试在构造函数中实例化tooltip并在鼠标悬停时显示它了吗?

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);
}

这个可以。但是,我尝试了:private ToolTip tT = new ToolTip();在mousehover事件之外,但那也不起作用。为什么在构造函数中实例化与在声明时实例化不同呢? - EatATaco
实际上,我刚刚再次尝试了那种方法,它起作用了。不确定第一次出了什么问题。再次感谢。 - EatATaco

1

仅仅使用设计师添加一个工具提示,生成的代码与问题中的代码截然不同。

Form1.Designer.cs:(为了可读性,将私有变量移到类的顶部)

partial class Form1
{
    private System.ComponentModel.IContainer components = null;
    private System.Windows.Forms.Label label1;
    private System.Windows.Forms.ToolTip toolTip1;

    // ...

    private void InitializeComponent()
    {
        this.components = new System.ComponentModel.Container();
        this.label1 = new System.Windows.Forms.Label();
        this.toolTip1 = new System.Windows.Forms.Tooltip(this.components);

        // ...

        this.toolTip1.SetToolTip(this.label1, "abc");

        // ...
    }
}

我相信你可以将提示框和容器的内容提取到你的组件中。


1

每次鼠标移动到您的控件上时,都会触发MouseHover事件。因此,每次事件被触发时,您都会创建一个新的工具提示。这就是为什么您会看到多个此小部件实例的原因。尝试使用Joseph的答案。


0

阅读MSDN,所有的都在那里!

你可以尝试另一个解决方案:


private System.Windows.Forms.ToolTip toolTip1;

private void YourControl_MouseHover(object sender, EventArgs e)
{
     toolTip1 = new System.Windows.Forms.ToolTip();
     this.toolTip1.SetToolTip(this.YourControl, "Your text here :) ");
     this.toolTip1.ShowAlways = true;
}

希望我能帮到你


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接