Getting the WinForms HelpProvider namespace for a control programatically using C#

We recently had an issue whereby we wanted to have a Windows Form control in a control library which could be presented with a HelpNamespace and HelpKeyword that could be customised based on the end product that the UI was integrated with.

The control itself automatically inherits the help of the parent, but when the control opens a child form that Windows Form doesn't know of the help information.

However, manually assigning the HelpNamespace to the UI control which it then passes to the form seemed tedious given that the form on which the control resides already knows the namespace, but how to get that namespace programatically.

The HelpProvider is a component, not a control so you need to use the following code.

If the control doesn't have a HelpProvider assigned directly, the controls' parent is queried.


/// <summary>
/// Returns the help namespace assigned to the specified control, or its parent form.
/// </summary>
/// <param name="control">The control for which the help namespace is to be returned.</param>
/// <returns>The help namespace assigned to the specified control, or its parent form.</returns>
/// <remarks>If there are multiple HelpProvider controls the namespace of the first control is returned.</remarks>
public static String GetHelpNamespace(Control control)
{
    try
    {
        foreach (FieldInfo field in control.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
        {
            if (field.FieldType == typeof(HelpProvider))
            {
                HelpProvider helpProvider = (HelpProvider)field.GetValue(control);
                return helpProvider.HelpNamespace;
            }
        }
        if (!(control is Form)) { return GetHelpNamespace(control.FindForm()); }
        return String.Empty;
    }
    catch (Exception ex)
    {
        String controlName = control == null ? "null" : control.Name;
        throw new WindowsFormsSupportException(String.Format(Resources.WindowsFormsSupport.GetHelpNamespaceException, controlName, ex.Message));
    }
}


Comments

Popular posts from this blog

Windows Server 2016, 2019, 2022, Windows 10 and Windows 11: Date and time "Some settings are managed by your organization".

TFTPD32 or TFTPD64 reports Bind error 10013 An attempt was made to access a socket in a way forbidden by its access permissions.

Enable function lock for F1-F12 on HP ZBook mobile workstations