C# Display a tooltip on disabled textbox (Form)

2020-02-12 08:46发布

问题:

I am trying to get a tooltip to display on a disabled textbox during a mouse over. I know because the control is disabled the following won't work:

private void textBox5_MouseHover(object sender, EventArgs e)
{
       // My tooltip display code here
}

How can I get the tooltip to display on a mouse over of a disabled control?

Many thanks

回答1:

MouseHover wont fire if control is disabled. Instead you can check in Form MouseMove event whether you hover the textbox

    public Form1()
    {
        InitializeComponent();
        textBox1.Enabled = false;
        toolTip.InitialDelay = 0;
    }

    private ToolTip toolTip = new ToolTip();
    private bool isShown = false;

    private void Form1_MouseMove(object sender, MouseEventArgs e)
    {
        if(textBox1 == this.GetChildAtPoint(e.Location))
        {
            if(!isShown)
            {
                toolTip.Show("MyToolTip", this, e.Location);
                isShown = true;
            }
        }
        else
        {
            toolTip.Hide(textBox1);
            isShown = false;
        }
    }



回答2:

You can also drag a ToolTip object from the Toolbox in designer onto the form. Then in the code you just call SetToolTip() and pass in the button or text box etc. you want the tool tip to assign to and the text you want it to show.

myToolTip.SetToolTip(myTextBox, "You just hovered over myTextBox!");