Visual Studio中截取F1帮助命令 [英] Visual Studio intercepting F1 help command

查看:935
本文介绍了Visual Studio中截取F1帮助命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

进出口寻找写一个Visual Studio插件,可以拦截默认的在线帮助指挥抢当F1帮助称为一个类或类型的MSDN库网址。

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.

例如说,我把我的光标放在它通常会自动打开浏览器并定位到字符串引用类型的帮助文档的关键字字符串,然后按F1。我想抓住传递给它到达浏览器之前,浏览器的URL。

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.

是否可以写一个Visual Studio插件/扩展,可以拦截默认的F1帮助命令??

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?

推荐答案

大约10年前,当我曾在微软,我写的规格在Visual Studio 2005中原来的在线F1功能,使我的知识是有点权威,但也有可能过时。 ; - )

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. ;-)

您不能更改的Visual Studio使用(至少我不知道如何去改变它)的网址,但你完全可以另写附加在抢断F1键绑定,使用的默认F1处理程序做同样的帮助上下文,并引导用户自己的URL或应用。

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.

首先,关于如何在线F1工作的一些信息:

First, some info about how Online F1 works:


  1. 在Visual Studio IDE推关键字组件进入F1帮助上下文,这是什么用户在做信息的属性包:如在代码编辑器当前的选择,类型的文件进行编辑,项目类型正在编辑等。

  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.

背景为URL并打开在MSDN指向浏览器。

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

在VS2012 HTML编辑器中按F1时,下面是一个示例URL,在这种情况下,当CSS属性宽度选择

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



在K参数上面是包含Visual Studio中的帮助上下文。帮助上下文包含两个关键词(文本字符串)和属性(名称/值对)的Visual Studio内使用各种窗口,告诉什么用户现在在做的IDE它。

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.

CSS编辑器推两个关键词:宽度,我选中,vs.csseditor的MSDN可以作为一个回退,如果使用,例如,我的选择未在MSDN找到。

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

这确保F1加载页面的正确的语言或技术,在此情况下的CSS。 (其它过滤器,.NET 4.0,有没有因为我已经加载了项目的目标是.NET 4.0)

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.

在MSDN上实际的帮助内容有元数据(由谁创作的文档球队手动设置)含有与该页面相关的关键字和名称/值上下文属性。例如,在MSDN上,当它存储在MSDN服务器 CSS width属性文档,具有与之相关联的关键字的列表(在这种情况下,宽)和内容属性的列表(在这种情况下:DevLang = CSS)。页面可以有多个关键字(如System.String,串)和多上下文属性(如DevLang = C#,DevLang = VB,等等)。

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.).

在关键字列表获取到MSDN联机F1的服务,算法是这样的事情,需要提醒的是,可能在过去几年发生了变化:

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. 采取的第一个关键字

  2. 找到相匹配的关键字

  3. 所有的网页排除其中有一个匹配的所有页面对于上下文属性名称(如DevLang),但不具有价值的比赛。这,例如,排除 Control.Width 页面因为它可能被标记为DevLang = C#,DevLang = VB。但是,也不排除没有DevLang属性页。

  4. 如果没有结果现在剩下还有剩余的多个关键词,再次开始以#1下一个关键字(按顺序),除非你跑出来的关键字。如果没有留下的关键字,执行一个备份的操作,其可以被返回的MSDN搜索结果的列表,可以显示一个不能找到网页或其它一些解决方案。

  5. 排名其余结果。我不记得确切的排名算法,并从那时起可能是变了,但我相信一般的想法是要表明,第一个匹配的更多的属性页,并首次展示更受欢迎的比赛。

  6. 显示最上面的结果在浏览器

  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

下面是关于如何在Visual Studio中的代码示例加载项可以:

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


  1. 接管F1键绑定

  2. 当按下F1,获得帮助上下文,并把它变成一组name = value对

  3. 的传递组name = value对成一些外部的代码做的F1要求的东西。

我要离开了所有的Visual Studio插件样板代码 - 如果你需要也应该有很多在谷歌的例子。

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;
    }
}

这篇关于Visual Studio中截取F1帮助命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆