Visual Studio intercepting F1 help command

后端 未结 2 2037
天命终不由人
天命终不由人 2021-01-02 07:31

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 ty

2条回答
  •  生来不讨喜
    2021-01-02 07:56

    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
    {
        /// The object for implementing an Add-in.
        /// 
        public class Connect : IDTExtensibility2, IDTCommandTarget
        {
            /// Implements the constructor for the Add-in object. Place your initialization code within this method.
            public Connect()
            {
            }
    
            MsdnExplorer.MainWindow Explorer = new MsdnExplorer.MainWindow();
    
            /// Implements the OnConnection method of the IDTExtensibility2 interface. Receives notification that the Add-in is being loaded.
            /// Root object of the host application.
            /// Describes how the Add-in is being loaded.
            /// Object representing this Add-in.
            /// 
            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.
                    }
                }
            }
    
            /// Implements the OnDisconnection method of the IDTExtensibility2 interface. Receives notification that the Add-in is being unloaded.
            /// Describes how the Add-in is being unloaded.
            /// Array of parameters that are host application specific.
            /// 
            public void OnDisconnection(ext_DisconnectMode disconnectMode, ref Array custom)
            {
            }
    
            /// Implements the OnAddInsUpdate method of the IDTExtensibility2 interface. Receives notification when the collection of Add-ins has changed.
            /// Array of parameters that are host application specific.
            ///        
            public void OnAddInsUpdate(ref Array custom)
            {
            }
    
            /// Implements the OnStartupComplete method of the IDTExtensibility2 interface. Receives notification that the host application has completed loading.
            /// Array of parameters that are host application specific.
            /// 
            public void OnStartupComplete(ref Array custom)
            {
            }
    
            /// Implements the OnBeginShutdown method of the IDTExtensibility2 interface. Receives notification that the host application is being unloaded.
            /// Array of parameters that are host application specific.
            /// 
            public void OnBeginShutdown(ref Array custom)
            {
            }
    
            /// Implements the QueryStatus method of the IDTCommandTarget interface. This is called when the command's availability is updated
            /// The name of the command to determine state for.
            /// Text that is needed for the command.
            /// The state of the command in the user interface.
            /// Text requested by the neededText parameter.
            /// 
            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;
                    }
                }
            }
    
    
            /// Implements the Exec method of the IDTCommandTarget interface. This is called when the command is invoked.
            /// The name of the command to execute.
            /// Describes how the command should be run.
            /// Parameters passed from the caller to the command handler.
            /// Parameters passed from the command handler to the caller.
            /// Informs the caller if the command was handled or not.
            /// 
            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 attributes = new List();
                        try
                        {
                            ContextAttributes highPri = contextAttributes == null ? null : contextAttributes.HighPriorityAttributes;
                            highPri.Refresh();
                            if (highPri != null)
                            {
                                foreach (ContextAttribute CA in highPri)
                                {
                                    List values = new List();
                                    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 values = new List();
                            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;
        }
    }
    

提交回复
热议问题