Display a tooltip over a button using Windows Forms

后端 未结 9 1709
梦谈多话
梦谈多话 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.

    0 讨论(0)
  • 2020-11-29 18:24

    The ToolTip is a single WinForms control that handles displaying tool tips for multiple elements on a single form.

    Say your button is called MyButton.

    1. Add a ToolTip control (under Common Controls in the Windows Forms toolbox) to your form.
    2. Give it a name - say MyToolTip
    3. Set the "Tooltip on MyToolTip" property of MyButton (under Misc in the button property grid) to the text that should appear when you hover over it.

    The tooltip will automatically appear when the cursor hovers over the button, but if you need to display it programmatically, call

    MyToolTip.Show("Tooltip text goes here", MyButton);
    

    in your code to show the tooltip, and

    MyToolTip.Hide(MyButton);
    

    to make it disappear again.

    0 讨论(0)
  • 2020-11-29 18:25

    The .NET framework provides a ToolTip class. Add one of those to your form and then on the MouseHover event for each item you would like a tooltip for, do something like the following:

    private void checkBox1_MouseHover(object sender, EventArgs e)
    {
        toolTip1.Show("text", checkBox1);
    }
    
    0 讨论(0)
提交回复
热议问题