如何在 C # Winforms 中向标签添加提示或工具提示?

看来,Label没有 HintToolTipHovertext的属性。那么,当鼠标靠近 Label时,显示提示、工具提示或悬浮文本的首选方法是什么呢?

116620 次浏览

You have to add a ToolTip control to your form first. Then you can set the text it should display for other controls.

Here's a screenshot showing the designer after adding a ToolTip control which is named toolTip1:

enter image description here

System.Windows.Forms.ToolTip ToolTip1 = new System.Windows.Forms.ToolTip();
ToolTip1.SetToolTip( Label1, "Label for Label1");
yourToolTip = new ToolTip();
//The below are optional, of course,


yourToolTip.ToolTipIcon = ToolTipIcon.Info;
yourToolTip.IsBalloon = true;
yourToolTip.ShowAlways = true;


yourToolTip.SetToolTip(lblYourLabel,"Oooh, you put your mouse over me.");

just another way to do it.

Label lbl = new Label();
new ToolTip().SetToolTip(lbl, "tooltip text here");

Just to share my idea...

I created a custom class to inherit the Label class. I added a private variable assigned as a Tooltip class and a public property, TooltipText. Then, gave it a MouseEnter delegate method. This is an easy way to work with multiple Label controls and not have to worry about assigning your Tooltip control for each Label control.

    public partial class ucLabel : Label
{
private ToolTip _tt = new ToolTip();


public string TooltipText { get; set; }


public ucLabel() : base() {
_tt.AutoPopDelay = 1500;
_tt.InitialDelay = 400;
//            _tt.IsBalloon = true;
_tt.UseAnimation = true;
_tt.UseFading = true;
_tt.Active = true;
this.MouseEnter += new EventHandler(this.ucLabel_MouseEnter);
}


private void ucLabel_MouseEnter(object sender, EventArgs ea)
{
if (!string.IsNullOrEmpty(this.TooltipText))
{
_tt.SetToolTip(this, this.TooltipText);
_tt.Show(this.TooltipText, this.Parent);
}
}
}

In the form or user control's InitializeComponent method (the Designer code), reassign your Label control to the custom class:

this.lblMyLabel = new ucLabel();

Also, change the private variable reference in the Designer code:

private ucLabel lblMyLabel;

I made a helper to make life easier.

public static class ControlUtilities1
{
public static Control AddToolTip(this Control control, string title, string text)
{
var toolTip = new ToolTip
{
ToolTipIcon = ToolTipIcon.None,
IsBalloon = true,
ShowAlways = true,
ToolTipTitle = title,
};
toolTip.SetToolTip(control, text);
return control;
}
}

Call it after controls are ready:

        InitializeComponent();
...
linkLabelChiValues.AddToolTip(title, text);

It's an way to keep consistent tool tip styles.