Display a tooltip over a button using Windows Forms

后端 未结 9 1844
梦谈多话
梦谈多话 2020-11-29 17:37

How can I display a tooltip over a button using Windows Forms?

9条回答
  •  余生分开走
    2020-11-29 18:22

    Lazy and compact storing text in the Tag property

    If you are a bit lazy and do not use the Tag property of the controls for anything else you can use it to store the tooltip text and assign MouseHover event handlers to all such controls in one go like this:

    private System.Windows.Forms.ToolTip ToolTip1;
    private void PrepareTooltips()
    {
        ToolTip1 = new System.Windows.Forms.ToolTip();
        foreach(Control ctrl in this.Controls)
        {
            if (ctrl is Button && ctrl.Tag is string)
            {
                ctrl.MouseHover += new EventHandler(delegate(Object o, EventArgs a)
                {
                    var btn = (Control)o;
                    ToolTip1.SetToolTip(btn, btn.Tag.ToString());
                });
            }
        }
    }
    

    In this case all buttons having a string in the Tag property is assigned a MouseHover event. To keep it compact the MouseHover event is defined inline using a lambda expression. In the event any button hovered will have its Tag text assigned to the Tooltip and shown.

提交回复
热议问题