65.9K
CodeProject is changing. Read more.
Home

Context-Sensitive Help for Toolstrip Items

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.44/5 (7 votes)

Jul 9, 2008

CPOL

1 min read

viewsIcon

37052

downloadIcon

186

How to bind context-sensitive help to .NET ToolStrip items.

Introduction

The Windows Forms library in the .NET Framework has great support for context sensitive help. You can assign a help topic for each control in your program. This topic will be shown automatically when you press F1, provided that the control has focus.

A problem arises when you try to do this for ToolStrip items, such as ToolStripButton or ToolStripComboBox. These classes are not controls, they are not derived from Control but from the ToolStripItem class. You will need some tricks to make context-sensitive help work with these objects.

Solution

A simple case are the classes derived from ToolStripControlHost, e.g., ToolStripComboBox. They create a control to draw themselves. So, we can just bind this control to a help topic, as shown in the following code snippet:

helpProvider1.SetHelpKeyword(toolStripComboBox1.Control, "Chapter_2.htm");
helpProvider1.SetHelpNavigator(toolStripComboBox1.Control, HelpNavigator.Topic);

If you want to bind context-sensitive help to other ToolStripItems, e.g., to the ToolStripButton, you'll need a little more work. First, you will need a custom HelpProvider:

class CustomHelpProvider: HelpProvider
{
    public override string GetHelpKeyword(Control ctl)
    {
        ToolStrip ts = ctl as ToolStrip;
        if (ts != null) {
            foreach (ToolStripItem item in ts.Items) {
                if (item.Selected) {
                    string keyword = item.Tag as string;
                    if (keyword != null)
                        return keyword;
                }
            }
        }
        return base.GetHelpKeyword(ctl);
    }
}

CustomHelpProvider looks if a ToolStripItem has focus (Selected property). If it's the case, it uses its Tag property to get the help keyword. Now, we just have to set up the ToolStrip and its items to work with our help provider:

// Register the tool strip at the help provider with an empty keyword.
helpProvider1.SetHelpKeyword(toolStrip1, "");
helpProvider1.SetHelpNavigator(toolStrip1, HelpNavigator.Topic);

// Set help keywords for the toolstrip buttons using Tag property.
toolStripButton1.Tag = "Chapter_3.htm";
toolStripButton2.Tag = "Chapter_4.htm";
toolStripButton3.Tag = "Chapter_5.htm";

That's it, now the ToolStripButtons have context-sensitive help.

As a further improvement, you may wish to derive your own class from ToolStripButton. This class will have a property for the help keyword instead of using the Tag property.