Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Visual Studio intercepting F1 help command

Im looking to write a visual studio addin that can intercept the default online help command and grab the MSDN library URL when F1 help is called on a class or type.

For example say I place my cursor on the keyword string and press F1 it usually automatically opens the browser and navigates to the help documentation for the string reference type. I want to grab the URL passed to the browser before it reaches the browser.

Is it possible to write a visual studio addin/extension that can intercept the default F1 help command ??

If the above can be done any pointers as to where to start?

like image 750
Luke Devonshire Avatar asked Dec 18 '12 22:12

Luke Devonshire


People also ask

How to turn off Zen mode in VS code?

Press Esc twice to exit Zen Mode.

What is F12 in Visual Studio?

Ctrl + F12 This hotkey is one of the most important hotkeys in the Visual Studio code editor window or instance. This hotkey is used to show the information, meaning, and description of the chosen symbol.

How do I use Visual Studio commands?

The Command window is used to execute commands or aliases directly in the Visual Studio integrated development environment (IDE). You can execute both menu commands and commands that do not appear on any menu. To display the Command window, choose Other Windows from the View menu, and select Command Window.


1 Answers

About 10 years ago, when I worked at Microsoft, I wrote the specification for the original "Online F1" feature in Visual Studio 2005. So my knowledge is somewhat authoritative but also likely out of date. ;-)

You can't change the URL that Visual Studio is using (at least I don't know how to change it), but you can simply write another add-in which steals the F1 key binding, uses the same help context that the default F1 handler does, and direct the user to your own URL or app.

First, some info about how Online F1 works:

  1. components of the Visual Studio IDE push keywords into the "F1 Help Context" which is a property bag of information about what the user is doing: e.g. current selection in the code editor, type of file being edited, type of project being edited, etc.

  2. when the user presses F1, the IDE packages that help context into a URL and opens a browser pointing at MSDN.

Here's a sample URL, in this case when pressing F1 in the VS2012 HTML editor when the CSS property "width" was selected

msdn.microsoft.com/query/dev11.query?
    appId=Dev11IDEF1&
    l=EN-US&
    k=k(width);
        k(vs.csseditor);
        k(TargetFrameworkMoniker-.NETFramework,Version%3Dv4.0);
        k(DevLang-CSS)&
    rd=true

The "k" parameter above is contains the help context inside visual studio. Help context contains both "keywords" (text strings) and "attributes" (name/value pairs) which various windows inside Visual Studio use to tell the IDE about what the user is doing right now.

The CSS editor pushed two keywords: "width" that I selected, and "vs.csseditor" which MSDN can use as a "fallback" if, for example, my selection is not found on MSDN.

There's also some contextual filtering attributes:

TargetFrameworkMoniker = NETFramework,Version=v4.0
DevLang=CSS

These ensure that F1 loads the page for the correct language or technology, in this case CSS. (The other filter for, .NET 4.0, is there because the project I have loaded is targeting .NET 4.0)

Note that context is ordered. The "width" keyword is more important than the ones below it.

The actual help content on MSDN has metadata (manually set by the teams who author the documentation) containing keywords and name/value context properties associated with that page. For example, the css width property documentation on MSDN, when it's stored on MSDN servers, has a list of keywords associated with it (in this case: "width") and a list of contextual properties (in this case: "DevLang=CSS"). Pages can have multiple keywords (e.g. "System.String", "String") and multiple context properties (e.g. "DevLang=C#", "DevLang=VB", etc.).

When the list of keywords gets to the MSDN Online F1 service, the algorithm is something like this, with the caveat that it may have changed in the last few years:

  1. take the first keyword
  2. find all pages which match that keyword
  3. exclude all pages which have a match for the contextual attribute name (e.g. "DevLang") but don't have a match for the value. This would, for example, exclude the Control.Width page because it would be marked "DevLang=C#", "DevLang=VB". But it would not exclude pages without the DevLang attribute.
  4. If no results are left but there are more keywords remaining, start again with #1 with the next keyword (in order) unless you run out of keywords. If there are no keywords left, perform a "backup" operation, which may be returning a list of MSDN search results, may be showing a "can't find it page", or some other solution.
  5. Rank the remaining results. I don't remember the exact ranking algorithm and it's probably changed since then, but I believe the general idea was to show pages that matched more attributes first, and show more popular matches first.
  6. Show the topmost result in the browser

Here's a code sample for how a Visual Studio add-in can:

  1. take over the F1 key binding
  2. when F1 is pressed, get the help context and turn it into a set of name=value pairs
  3. pass that set of name=value pairs into some external code to do something with the F1 request.

I'm leaving out all the Visual Studio add-in boilerplate code-- if you need that too, there should be lots of examples in Google.

using System;
using Extensibility;
using EnvDTE;
using EnvDTE80;
using Microsoft.VisualStudio.CommandBars;
using System.Resources;
using System.Reflection;
using System.Globalization;
using System.Collections;
using System.Collections.Generic;
using System.Text;

namespace ReplaceF1
{
    /// <summary>The object for implementing an Add-in.</summary>
    /// <seealso class='IDTExtensibility2' />
    public class Connect : IDTExtensibility2, IDTCommandTarget
    {
        /// <summary>Implements the constructor for the Add-in object. Place your initialization code within this method.</summary>
        public Connect()
        {
        }

        MsdnExplorer.MainWindow Explorer = new MsdnExplorer.MainWindow();

        /// <summary>Implements the OnConnection method of the IDTExtensibility2 interface. Receives notification that the Add-in is being loaded.</summary>
        /// <param term='application'>Root object of the host application.</param>
        /// <param term='connectMode'>Describes how the Add-in is being loaded.</param>
        /// <param term='addInInst'>Object representing this Add-in.</param>
        /// <seealso class='IDTExtensibility2' />
        public void OnConnection(object application, ext_ConnectMode connectMode, object addInInst, ref Array custom)
        {
            _applicationObject = (DTE2)application;
            _addInInstance = (AddIn)addInInst;
            if(connectMode == ext_ConnectMode.ext_cm_UISetup)
            {
                object []contextGUIDS = new object[] { };
                Commands2 commands = (Commands2)_applicationObject.Commands;
                string toolsMenuName;

                try
                {
                    // If you would like to move the command to a different menu, change the word "Help" to the 
                    //  English version of the menu. This code will take the culture, append on the name of the menu
                    //  then add the command to that menu. You can find a list of all the top-level menus in the file
                    //  CommandBar.resx.
                    ResourceManager resourceManager = new ResourceManager("ReplaceF1.CommandBar", Assembly.GetExecutingAssembly());
                    CultureInfo cultureInfo = new System.Globalization.CultureInfo(_applicationObject.LocaleID);
                    string resourceName = String.Concat(cultureInfo.TwoLetterISOLanguageName, "Help");
                    toolsMenuName = resourceManager.GetString(resourceName);
                }
                catch
                {
                    //We tried to find a localized version of the word Tools, but one was not found.
                    //  Default to the en-US word, which may work for the current culture.
                    toolsMenuName = "Help";
                }

                //Place the command on the tools menu.
                //Find the MenuBar command bar, which is the top-level command bar holding all the main menu items:
                Microsoft.VisualStudio.CommandBars.CommandBar menuBarCommandBar = ((Microsoft.VisualStudio.CommandBars.CommandBars)_applicationObject.CommandBars)["MenuBar"];

                //Find the Tools command bar on the MenuBar command bar:
                CommandBarControl toolsControl = menuBarCommandBar.Controls[toolsMenuName];
                CommandBarPopup toolsPopup = (CommandBarPopup)toolsControl;

                //This try/catch block can be duplicated if you wish to add multiple commands to be handled by your Add-in,
                //  just make sure you also update the QueryStatus/Exec method to include the new command names.
                try
                {
                    //Add a command to the Commands collection:
                    Command command = commands.AddNamedCommand2(_addInInstance, 
                        "ReplaceF1", 
                        "MSDN Advanced F1", 
                        "Brings up context-sensitive Help via the MSDN Add-in", 
                        true, 
                        59, 
                        ref contextGUIDS, 
                        (int)vsCommandStatus.vsCommandStatusSupported+(int)vsCommandStatus.vsCommandStatusEnabled, 
                        (int)vsCommandStyle.vsCommandStylePictAndText, 
                        vsCommandControlType.vsCommandControlTypeButton);
                    command.Bindings = new object[] { "Global::F1" };
                }
                catch(System.ArgumentException)
                {
                    //If we are here, then the exception is probably because a command with that name
                    //  already exists. If so there is no need to recreate the command and we can 
                    //  safely ignore the exception.
                }
            }
        }

        /// <summary>Implements the OnDisconnection method of the IDTExtensibility2 interface. Receives notification that the Add-in is being unloaded.</summary>
        /// <param term='disconnectMode'>Describes how the Add-in is being unloaded.</param>
        /// <param term='custom'>Array of parameters that are host application specific.</param>
        /// <seealso class='IDTExtensibility2' />
        public void OnDisconnection(ext_DisconnectMode disconnectMode, ref Array custom)
        {
        }

        /// <summary>Implements the OnAddInsUpdate method of the IDTExtensibility2 interface. Receives notification when the collection of Add-ins has changed.</summary>
        /// <param term='custom'>Array of parameters that are host application specific.</param>
        /// <seealso class='IDTExtensibility2' />       
        public void OnAddInsUpdate(ref Array custom)
        {
        }

        /// <summary>Implements the OnStartupComplete method of the IDTExtensibility2 interface. Receives notification that the host application has completed loading.</summary>
        /// <param term='custom'>Array of parameters that are host application specific.</param>
        /// <seealso class='IDTExtensibility2' />
        public void OnStartupComplete(ref Array custom)
        {
        }

        /// <summary>Implements the OnBeginShutdown method of the IDTExtensibility2 interface. Receives notification that the host application is being unloaded.</summary>
        /// <param term='custom'>Array of parameters that are host application specific.</param>
        /// <seealso class='IDTExtensibility2' />
        public void OnBeginShutdown(ref Array custom)
        {
        }

        /// <summary>Implements the QueryStatus method of the IDTCommandTarget interface. This is called when the command's availability is updated</summary>
        /// <param term='commandName'>The name of the command to determine state for.</param>
        /// <param term='neededText'>Text that is needed for the command.</param>
        /// <param term='status'>The state of the command in the user interface.</param>
        /// <param term='commandText'>Text requested by the neededText parameter.</param>
        /// <seealso class='Exec' />
        public void QueryStatus(string commandName, vsCommandStatusTextWanted neededText, ref vsCommandStatus status, ref object commandText)
        {
            if(neededText == vsCommandStatusTextWanted.vsCommandStatusTextWantedNone)
            {
                if(commandName == "ReplaceF1.Connect.ReplaceF1")
                {
                    status = (vsCommandStatus)vsCommandStatus.vsCommandStatusSupported|vsCommandStatus.vsCommandStatusEnabled;
                    return;
                }
            }
        }


        /// <summary>Implements the Exec method of the IDTCommandTarget interface. This is called when the command is invoked.</summary>
        /// <param term='commandName'>The name of the command to execute.</param>
        /// <param term='executeOption'>Describes how the command should be run.</param>
        /// <param term='varIn'>Parameters passed from the caller to the command handler.</param>
        /// <param term='varOut'>Parameters passed from the command handler to the caller.</param>
        /// <param term='handled'>Informs the caller if the command was handled or not.</param>
        /// <seealso class='Exec' />
        public void Exec(string commandName, vsCommandExecOption executeOption, ref object varIn, ref object varOut, ref bool handled)
        {
            if(executeOption == vsCommandExecOption.vsCommandExecOptionDoDefault)
            {
                if (commandName == "ReplaceF1.Connect.ReplaceF1")
                {
                    // Get a reference to Solution Explorer.
                    Window activeWindow = _applicationObject.ActiveWindow;

                    ContextAttributes contextAttributes = activeWindow.DTE.ContextAttributes;
                    contextAttributes.Refresh();

                    List<string> attributes = new List<string>();
                    try
                    {
                        ContextAttributes highPri = contextAttributes == null ? null : contextAttributes.HighPriorityAttributes;
                        highPri.Refresh();
                        if (highPri != null)
                        {
                            foreach (ContextAttribute CA in highPri)
                            {
                                List<string> values = new List<string>();
                                foreach (string value in (ICollection)CA.Values)
                                {
                                    values.Add(value);
                                }
                                string attribute = CA.Name + "=" + String.Join(";", values.ToArray());
                                attributes.Add(CA.Name + "=");
                            }
                        }
                    }
                    catch (System.Runtime.InteropServices.COMException e)
                    {
                        // ignore this exception-- means there's no High Pri values here
                        string x = e.Message;
                    }
                    catch (System.Reflection.TargetInvocationException e)
                    {
                        // ignore this exception-- means there's no High Pri values here
                        string x = e.Message;
                    }
                    catch (System.Exception e)
                    {
                        System.Windows.Forms.MessageBox.Show(e.Message);
                        // ignore this exception-- means there's no High Pri values here
                        string x = e.Message;
                    }

                    // fetch context attributes that are not high-priority
                    foreach (ContextAttribute CA in contextAttributes)
                    {
                        List<string> values = new List<string>();
                        foreach (string value in (ICollection)CA.Values)
                        {
                            values.Add (value);
                        }
                        string attribute = CA.Name + "=" + String.Join(";", values.ToArray());
                        attributes.Add (attribute);
                    }

                    // Replace this call with whatever you want to do with the help context info 
                    HelpHandler.HandleF1 (attributes);
                }
            }
        }
        private DTE2 _applicationObject;
        private AddIn _addInInstance;
    }
}
like image 64
Justin Grant Avatar answered Oct 08 '22 02:10

Justin Grant