本文是小编为大家收集整理的关于Visual Studio拦截F1帮助命令的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。
问题描述
我想编写一个可以拦截默认在线帮助命令的Visual Studio addin,并在 f1 时抓取MSDN库URL.
例如,说我将光标放在关键字字符串上,然后按 f1 通常会自动打开浏览器并导航到字符串参考类型的帮助文档.我想在浏览器到达浏览器之前抓住传递给浏览器的URL.
是否可以编写可以拦截默认F1帮助命令??
的Visual Studio addin/扩展程序如果可以做任何从哪里开始的指示?
推荐答案
大约10年前,当我在Microsoft工作时,我在Visual Studio 2005中写了原始"在线F1"功能的规范.因此,我的知识有些权威,但也可能过时. ; - )
您不能更改Visual Studio使用的URL(至少我不知道如何更改),但是您可以简单地编写另一个窃取F1键绑定的加载项,使用相同的帮助上下文默认的F1处理程序可以将用户引导到您自己的URL或应用程序.
首先,有关在线F1的工作方式的一些信息:
-
Visual Studio IDE的组件将关键字推入" F1帮助上下文",这是有关用户正在执行的信息的属性袋:例如,代码编辑器中的当前选择,正在编辑的文件类型,正在编辑的项目类型等.
-
当用户按F1时,可以帮助上下文中的IDE软件包,并打开指向MSDN的浏览器.
这是一个示例URL,在这种情况下,当选择CSS属性" width"
时按VS2012 HTML编辑器中的F1时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内部的帮助上下文.帮助上下文包含"关键字"(文本字符串)和"属性"(名称/值对),这些Windows在Visual Studio中使用这些Windows用来告诉IDE有关用户现在在做什么.
CSS编辑器推出了两个关键字:我选择的"宽度"和" vs.csseditor",如果在MSDN上找不到我的选择,则MSDN可以用作"后备".
还有一些上下文过滤属性:
TargetFrameworkMoniker = NETFramework,Version=v4.0 DevLang=CSS
这些确保F1为正确的语言或技术加载页面,在这种情况下为CSS. (.NET 4.0的另一个过滤器,因为我已加载的项目是目标.NET 4.0)
请注意,上下文已排序. "宽度"关键字比下面的关键字更重要.
MSDN上的实际帮助内容具有包含与该页面关联的关键字和名称/价值上下文属性的撰写文档的团队设置).例如, css width Property Documentation 在MSDN上,存储在MSDN服务器上,具有与之关联的关键字列表(在这种情况下:" width")和上下文属性列表(在这种情况下:" devlang = css").页面可以具有多个关键字(例如" System.String"," String")和多个上下文属性(例如" Devlang = C#"," Devlang = Vb"等).
当关键字列表到达MSDN在线F1服务时,该算法就是这样的,并且在过去几年中可能已经改变了警告:
- 以第一个关键字
- 找到与该关键字匹配的所有页面
- 排除具有匹配上下文属性名称(例如" devlang")但没有该值匹配的所有页面.例如,这将排除 control.width 页面,因为它会标记为" devlang = c#"," devlang = vb".但是,如果没有Devlang属性,它不会排除页面.
- 如果没有结果,但是剩下更多的关键字,请从#1开始,下一个关键字(按顺序),除非您用完关键字.如果没有剩下的关键字,请执行"备份"操作,该操作可能会返回MSDN搜索结果列表,可能会显示一个"找不到它的页面"或其他解决方案.
- 对剩余的结果进行排名.我不记得确切的排名算法,从那以后它可能发生了变化,但是我相信总体想法是显示首先匹配更多属性的页面,并首先显示更受欢迎的匹配项.
- 在浏览器中显示最高结果
这是视觉工作室加载项如何可以:
的代码示例- 接管F1键绑定
- 按下F1时,获取帮助上下文并将其变成一组名称= value对
- 将一组名称=值对传递到一些外部代码中,以通过F1请求做某事.
我省略了所有Visual Studio加载项的样板代码 - 如果您也需要,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; } }
其他推荐答案
所有人都非常令人兴奋,但可能会过时设计吗? 我像大多数人一样有可编程的鼠标.我设置了一个要搜索的按钮. IE单击Word,浏览器为Word打开"单词"的搜索引擎.通常,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.
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?
推荐答案
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:
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.
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:
- take the first keyword
- find all pages which match that keyword
- 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.
- 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.
- 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.
- Show the topmost result in the browser
Here's a code sample for how a Visual Studio add-in can:
- take over the F1 key binding
- when F1 is pressed, get the help context and turn it into a set of name=value pairs
- 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; } }
其他推荐答案
All very exciting but potentially over engineered? I have a programmable mouse like most do. I have set one of the buttons to search. ie Click on word and browser opens in favourite search engine for the word. Usually the MSDN help is on that list. AS Is SO links. I like effective and simple soultions :-)