简体   繁体   中英

How to enable/disable tool tips with code

How to enable/disable tooltips with code. I am able to enable tooltips for a button with code on form load, but cannot turn tooltips off with code for a checkbox.

private void Form1_Load(object sender, EventArgs e)
{
    // Create the ToolTip and associate with the Form container.
    ToolTip toolTip1 = new ToolTip();

    // Set up the ToolTip text for a Button.
    toolTip1.SetToolTip(this.btnRunExtApp, "Run the external application");
}

Works perfectly.

I am now trying to make a user option to turn on/off the tooltip with a checkbox.

private void ChkEnableTips_CheckedChanged(object sender, EventArgs e)
{
    ToolTip toolTip1 = new ToolTip();

    if (ChkEnableTips.Checked == true)
    {
        toolTip1.SetToolTip(this.btnRunExtApp, "Run the external application");
    }
    if (ChkEnableTips.Checked == false)
    {               
        toolTip1.SetToolTip(this.btnRunExtApp, null);
    }
}

Maybe it is because I am declaring toolTip1 again? I tried to change it to toolTip2 but this did not work either. But if I do not declare it at all in ChkEnableTips_CheckedChanged then I get an error (The name 'toolTip1' does not exist in the current context).

Yes it is because you declare it again. Write to the top of your class a global variable.

ToolTip toolTip1 = new ToolTip();

Then events (also the constructor) can use it:

private void ChkEnableTips_CheckedChanged(object sender, EventArgs e)
{
    if (ChkEnableTips.Checked == true)
        toolTip1.SetToolTip(this.btnRunExtApp, "Run the external application");
    if (ChkEnableTips.Checked == false)
        toolTip1.SetToolTip(this.btnRunExtApp, null);
}

Do not set toolTip1 in Load event, go to the designer view instead and set your checkbox to be ticked by default. This will raise the event anyway and the handler above does the job for you. Also this way you avoid a 2nd call to SetToolTip() .

(Btw, some info for your future design when you want init in constructor - instead of Load -: the field initialization happens before the lines in the constructor.)

Edit:

Maybe there is a component in the Toolbox called ToolTip. You can drag and drop. It does not change anything! just moves this line:

ToolTip toolTip1 = new ToolTip();

To the designer.cs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM