How can I add a hint or tooltip to a label in C# Winforms?

前端 未结 5 2043
不知归路
不知归路 2021-01-31 06:43

It seems that the Label has no Hint or ToolTip or Hovertext property. So what is the preferred method to show a hint, tooltip

5条回答
  •  执笔经年
    2021-01-31 07:23

    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;
    

提交回复
热议问题