private void AddGenerateCodeBtn() { Command findCommand = null; object[] contextUIGuids = new object[] { }; CommandBarButton findCommandBarButtonButton = null; Commands2 commands = (Commands2)_applicationObject.Commands; CommandBars cmdBars = (CommandBars)_applicationObject.CommandBars; if (findCommand == null) { findCommand = commands.AddNamedCommand2( _addInInstance, "GenerateCode", "GenerateCode", "GenerateCode", true, 59, ref contextUIGuids, (int)vsCommandStatus.vsCommandStatusSupported + (int)vsCommandStatus.vsCommandStatusEnabled, (int)vsCommandStyle.vsCommandStylePictAndText, vsCommandControlType.vsCommandControlTypeButton); } if (findCommand != null) { //解决方案 CommandBar codeWindowCommandBar3 = cmdBars["Project"]; if (codeWindowCommandBar3 != null) { findCommandBarButtonButton = (CommandBarButton)findCommand.AddControl( codeWindowCommandBar3, codeWindowCommandBar3.Controls.Count + 1); findCommandBarButtonButton.Caption = "rx_orm 强类型开发设置"; } } }
/// <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; commandBars = (CommandBars)_applicationObject.CommandBars; try { commandBar = (CommandBar)commandBars["Code Window"]; //Add a command to the Commands collection: command = commands.AddNamedCommand2(_addInInstance, "ReviewCode", "ReviewCode", "Executes the command for ReviewCode", true, 59, ref contextGUIDS, (int)vsCommandStatus.vsCommandStatusSupported + (int)vsCommandStatus.vsCommandStatusEnabled, (int)vsCommandStyle.vsCommandStylePictAndText, vsCommandControlType.vsCommandControlTypeButton); //Command command2 = commands.AddNamedCommand2(_addInInstance,"Review Code","MyaddIn2","Execute the process for review code", true,59, ref contextGUIDS, (int)vsCommandStatus.vsCommandStatusSupported+(int)vsCommandStatus.vsCommandStatusEnabled, (int)vsCommandStyle.vsCommandStylePictAndText, vsCommandControlType.vsCommandControlTypeButton); //Add a control for the command to the tools menu: if ((command != null) && (commandBar != null)) { //command.AddControl(toolsPopup.CommandBar, 1); command.AddControl(commandBar, 1); } Buisness.InteractWindow.OpenPendingChangesWindow((CommandBars)_applicationObject.CommandBars); } 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. } } }
public static Command add_NamedCommand(this CommandBarPopup commandBarPopup, DTE2 dte2, AddIn addIn, string Name, string ButtonText, string ToolTip, bool MSOButton, object Bitmap) { object[] contextGUIDS = new object[] { }; Commands2 commands = (Commands2)dte2.Commands; Command command = commands.AddNamedCommand2(addIn, Name, ButtonText, ToolTip, MSOButton, Bitmap, ref contextGUIDS, (int)vsCommandStatus.vsCommandStatusSupported + (int)vsCommandStatus.vsCommandStatusEnabled, (int)vsCommandStyle.vsCommandStylePictAndText, vsCommandControlType.vsCommandControlTypeButton); //Add a control for the command to the tools menu: if ((command != null) && (commandBarPopup != null)) { command.AddControl(commandBarPopup.CommandBar, 1); return(command); } return(null); }
/// <summary>实现 IDTExtensibility2 接口的 OnConnection 方法。接收正在加载外接程序的通知。</summary> /// <param term='Application'>宿主应用程序的根对象。</param> /// <param term='ConnectMode'>描述外接程序的加载方式。</param> /// <param term='AddInInst'>表示此外接程序的对象。</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; try { CommandBar menuBarCommandBar; CommandBarControl toolsControl; CommandBarPopup toolsPopup; CommandBarControl commandBarControl; //将一个命令添加到 Commands 集合: Command command = commands.AddNamedCommand2(addInInstance, "PasteXmlAsLinq", "Paste XML as XElement", "Pastes the XML on the clipboard as C# Linq To Xml code", true, 59, ref contextGUIDS, (int)vsCommandStatus.vsCommandStatusSupported + (int)vsCommandStatus.vsCommandStatusEnabled, (int)vsCommandStyle.vsCommandStylePictAndText, vsCommandControlType.vsCommandControlTypeButton); String editMenuName; //查找 MenuBar 命令栏,该命令栏是容纳所有主菜单项的顶级命令栏: menuBarCommandBar = ((CommandBars)applicationObject.CommandBars)["MenuBar"]; try { // 此代码将获取区域性,将其追加到菜单项的名称中, // 然后将此命令添加到菜单中。您可以在以下文件中看到全部顶级菜单的列表: // CommandBar.resx. System.Resources.ResourceManager resourceManager = new System.Resources.ResourceManager("PasteXmlAsLinq.CommandBar", System.Reflection.Assembly.GetExecutingAssembly()); System.Threading.Thread thread = System.Threading.Thread.CurrentThread; System.Globalization.CultureInfo cultureInfo = thread.CurrentUICulture; editMenuName = resourceManager.GetString(String.Concat(cultureInfo.TwoLetterISOLanguageName, "Edit")); toolsControl = menuBarCommandBar.Controls["Edit"]; } catch (Exception) { // 我们尝试查找 Edit 一词的本地化版本,但未能找到。 // 默认值为 en-US 一词,该值可能适用于当前区域性。 toolsControl = menuBarCommandBar.Controls["Edit"]; } //将此命令置于“编辑”菜单上。 toolsPopup = (CommandBarPopup)toolsControl; int pasteControlIndex = 1; //查找“粘贴”控件,以便可在其后添加新的元素。 foreach (CommandBarControl commandBar in toolsPopup.CommandBar.Controls) { if (String.Compare(commandBar.Caption, "&Paste", StringComparison.OrdinalIgnoreCase) == 0) { pasteControlIndex = commandBar.Index + 1; break; } } //在 MenuBar 命令栏上查找相应的命令栏: commandBarControl = (CommandBarControl)command.AddControl(toolsPopup.CommandBar, pasteControlIndex); } catch (Exception) { } } }
/// <summary>实现 IDTExtensibility2 接口的 OnConnection 方法。接收正在加载外接程序的通知。</summary> /// <param term='application'>宿主应用程序的根对象。</param> /// <param term='connectMode'>描述外接程序的加载方式。</param> /// <param term='addInInst'>表示此外接程序的对象。</param> /// <seealso class='IDTExtensibility2' /> public void OnConnection(object application, ext_ConnectMode connectMode, object addInInst, ref Array custom) { _applicationObject = (DTE2)application; _addInInstance = (AddIn)addInInst; m_serviceProvider = new Microsoft.VisualStudio.Shell.ServiceProvider(_applicationObject as Microsoft.VisualStudio.OLE.Interop.IServiceProvider); if (connectMode == ext_ConnectMode.ext_cm_Startup) { try { _commands = (Commands2)_applicationObject.Commands; _commitem.Install(_applicationObject, _addInInstance, _commands); string err = InitBaseCode.InitBaseDll(); if (err != null) { FrmCompileResault.ShowCompileResault(null, err, "错误"); } } catch (Exception ex) { FrmCompileResault.ShowCompileResault(null, ex.ToString(), "错误"); } } }
/// <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; _actionMgr = new ActionManager(); _handler = new MenuActionHandler(_applicationObject); if (connectMode == ext_ConnectMode.ext_cm_AfterStartup) { object[] contextGUIDS = new object[] { }; Commands2 commands = (Commands2)_applicationObject.Commands; // get popUp command bars where commands will be registered. CommandBars cmdBars = (CommandBars)(_applicationObject.CommandBars); CommandBar vsBarCodeWindow = cmdBars["Code Window"]; //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 { CommandBarBuilder builder = new CommandBarBuilder(_actionMgr, _handler); builder.BuildMenu(vsBarCodeWindow.Controls, MenuXml.Load(@"C:\Corey Derochie\test.xml")); } catch (System.ArgumentException argEx) { System.Diagnostics.Debug.Write("Exception in HintPaths:" + argEx.ToString()); //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 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; try { CommandBar menuBarCommandBar; CommandBarControl toolsControl; CommandBarPopup toolsPopup; CommandBarControl commandBarControl; //Add a command to the Commands collection: Command command = commands.AddNamedCommand2(addInInstance, "PasteXmlAsLinq", "Paste XML as XElement", "Pastes the XML on the clipboard as C# Linq To Xml code", true, 59, ref contextGUIDS, (int)vsCommandStatus.vsCommandStatusSupported + (int)vsCommandStatus.vsCommandStatusEnabled, (int)vsCommandStyle.vsCommandStylePictAndText, vsCommandControlType.vsCommandControlTypeButton); String editMenuName; //Find the MenuBar command bar, which is the top-level command bar holding all the main menu items: menuBarCommandBar = ((CommandBars)applicationObject.CommandBars)["MenuBar"]; try { // This code will take the culture, append on the name of the menuitem, // then add the command to the menu. You can find a list of all the top-level menus in the file // CommandBar.resx. System.Resources.ResourceManager resourceManager = new System.Resources.ResourceManager("PasteXmlAsLinq.CommandBar", System.Reflection.Assembly.GetExecutingAssembly()); System.Threading.Thread thread = System.Threading.Thread.CurrentThread; System.Globalization.CultureInfo cultureInfo = thread.CurrentUICulture; editMenuName = resourceManager.GetString(String.Concat(cultureInfo.TwoLetterISOLanguageName, "Edit")); toolsControl = menuBarCommandBar.Controls["Edit"]; } catch (Exception) { // We tried to find a localized version of the word Edit, but one was not found. // Default to the en-US word, which may work for the current culture. toolsControl = menuBarCommandBar.Controls["Edit"]; } //Place the command on the edit menu. toolsPopup = (CommandBarPopup)toolsControl; int pasteControlIndex = 1; //Find the paste control so that the new element can be added after it. foreach (CommandBarControl commandBar in toolsPopup.CommandBar.Controls) { if (String.Compare(commandBar.Caption, "&Paste", StringComparison.OrdinalIgnoreCase) == 0) { pasteControlIndex = commandBar.Index + 1; break; } } //Find the appropriate command bar on the MenuBar command bar: commandBarControl = (CommandBarControl)command.AddControl(toolsPopup.CommandBar, pasteControlIndex); } catch (Exception) { } } }
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 = "Tools"; Microsoft.VisualStudio.CommandBars.CommandBar menuBarCommandBar = ((Microsoft.VisualStudio.CommandBars.CommandBars)_applicationObject.CommandBars)["MenuBar"]; CommandBarControl toolsControl = menuBarCommandBar.Controls[toolsMenuName]; CommandBarPopup toolsPopup = (CommandBarPopup)toolsControl; try { Command command = commands.AddNamedCommand2(_addInInstance, "SPProjectServiceAddIn", "SPProjectServiceAddIn", "Executes the command for SPProjectServiceAddIn", true, 59, ref contextGUIDS, (int)vsCommandStatus.vsCommandStatusSupported + (int)vsCommandStatus.vsCommandStatusEnabled, (int)vsCommandStyle.vsCommandStylePictAndText, vsCommandControlType.vsCommandControlTypeButton); if ((command != null) && (toolsPopup != null)) { command.AddControl(toolsPopup.CommandBar, 1); } } catch (System.ArgumentException) { } } TestSPService(); }
/// <summary> /// Adds a new Command and creates a new CommandBar control both of which /// can be returned via the AddCommandReturn object that holds refs to both. /// </summary> /// <param name="name">The name of the Command. Must be handled in the Addin</param> /// <param name="caption">The Caption</param> /// <param name="description">Tooltip Text</param> /// <param name="iconId">Icon Id if you use a custom icon. Otherwise use 0</param> /// <param name="commandBar">The Command bar that this command will attach to</param> /// <param name="insertionIndex">The InsertionIndex for this CommandBar</param> /// <param name="beginGroup">Are we starting a new group on the toolbar (above)</param> /// <param name="hotKey">Optional hotkey. Format: "Global::alt+f1"</param> /// <returns>AddCommandReturn object that contains a Command and CommandBarControl object that were created</returns> private void AddCommand(string name, string caption, string description, int iconId, CommandBar commandBar, int insertionIndex, bool beginGroup, string hotKey) { object[] contextGuids = new object[] { }; // *** Check to see if the Command exists already to be safe string commandName = _addInInstance.ProgID + "." + name; Command command = null; try { command = _visualStudioInstance.Commands.Item(commandName, -1); } catch {; } // *** If not create it! if (command == null) { Commands2 commands = (Commands2)_visualStudioInstance.Commands; //Add a command to the Commands collection: //loading the Custom image icon //http://tech.einaregilsson.com/2009/11/20/easy-way-to-have-custom-icons-in-visual-studio-addin/ command = commands.AddNamedCommand2(_addInInstance, name, caption, description, false, iconId, ref contextGuids, (int)vsCommandStatus.vsCommandStatusSupported + (int)vsCommandStatus.vsCommandStatusEnabled, (int)vsCommandStyle.vsCommandStylePictAndText, vsCommandControlType.vsCommandControlTypeButton); } CommandBarControl cb = (CommandBarControl)command.AddControl(commandBar, insertionIndex); cb.BeginGroup = beginGroup; }
/// <summary> /// /// </summary> /// <param name="json"></param> /// <returns></returns> public bool startup(string json) { object[] contextGUIDS = new object[] { }; Commands2 commands = _dte.Commands as Commands2; CommandBar menuBar = (_dte.CommandBars as CommandBars)["MenuBar"]; try { int index = 9; foreach (CommandBarControl control in menuBar.Controls) { if (control.Type == MsoControlType.msoControlPopup) { CommandBarPopup temp = control as CommandBarPopup; if (temp.CommandBar.Name == "Tools") { index = temp.Index + 1; break; } } } CommandBarPopup popup = menuBar.Controls.Add(MsoControlType.msoControlPopup, Type.Missing, Type.Missing, index, true) as CommandBarPopup; popup.CommandBar.Name = "Emmet"; popup.Caption = "E&mmet"; CommandBar commandBar = popup.CommandBar; Command command = null; CommandBarButton button = null; DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Action[])); MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(json)); Action[] actions = serializer.ReadObject(stream) as Action[]; foreach (var action in actions) { if (action.type == "action") { command = commands.AddNamedCommand2(_addIn, action.name, action.label, action.label, false, Type.Missing, ref contextGUIDS, 1); button = command.AddControl(commandBar, commandBar.Controls.Count + 1) as CommandBarButton; } else { CommandBar control = commands.AddCommandBar(action.name, vsCommandBarType.vsCommandBarTypeMenu, commandBar, commandBar.Controls.Count + 1) as CommandBar; if (action.items != null) { foreach (var item in action.items) { command = commands.AddNamedCommand2(_addIn, item.name, item.label, item.label, false, Type.Missing, ref contextGUIDS, 1); button = command.AddControl(control, control.Controls.Count + 1) as CommandBarButton; } } } } popup.Visible = true; } catch { return false; } return true; }
/// <summary>实现 IDTExtensibility2 接口的 OnConnection 方法。接收正在加载外接程序的通知。</summary> /// <param term='application'>宿主应用程序的根对象。</param> /// <param term='connectMode'>描述外接程序的加载方式。</param> /// <param term='addInInst'>表示此外接程序的对象。</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; // 查找 解决方案 命令栏 Microsoft.VisualStudio.CommandBars.CommandBar menuBarCommandBar = ((Microsoft.VisualStudio.CommandBars.CommandBars)_applicationObject.CommandBars)["Solution"]; //如果希望添加多个由您的外接程序处理的命令,可以重复此 try/catch 块, // 只需确保更新 QueryStatus/Exec 方法,使其包含新的命令名。 try { //将一个命令添加到 Commands 集合: Command command = commands.AddNamedCommand2(_addInInstance, "ReadOnlyCleaner", "移除只读属性", "移除解决方案下所有文件的只读属性", true, 58, ref contextGUIDS, (int)vsCommandStatus.vsCommandStatusSupported + (int)vsCommandStatus.vsCommandStatusEnabled, (int)vsCommandStyle.vsCommandStylePictAndText, vsCommandControlType.vsCommandControlTypeButton); //将对应于该命令的控件添加到“工具”菜单: if ((command != null)) { command.AddControl(menuBarCommandBar, 1); } } catch (System.ArgumentException) { //如果出现此异常,原因很可能是由于具有该名称的命令 // 已存在。如果确实如此,则无需重新创建此命令,并且 // 可以放心忽略此异常。 } } }
/// <summary> /// Adds the command bar. /// </summary> /// <param name="commandName">Name of the command.</param> /// <returns>The command bar.</returns> public CommandBar AddCommandBar(string commandName) { TraceService.WriteLine("CommandManager::AddCommandBar commandName=" + commandName); Commands2 commands = (Commands2)this.VSInstance.ApplicationObject.Commands; CommandBarPopup toolsMenuPopUp = this.VSInstance.ApplicationObject.GetToolsMenuPopUp(); CommandBar commandBar = null; for (int i = 1; i <= toolsMenuPopUp.CommandBar.Controls.Count; i++) { if (toolsMenuPopUp.CommandBar.Controls[i].Caption == commandName) { TraceService.WriteLine("CommandManager::AddCommandBar commandFound in collection"); CommandBarPopup commandBarPopup = (CommandBarPopup)toolsMenuPopUp.CommandBar.Controls[i]; commandBar = commandBarPopup.CommandBar; break; } } if (commandBar == null) { TraceService.WriteLine("CommandManager::AddCommandBar creating command"); return((CommandBar)commands.AddCommandBar(commandName, vsCommandBarType.vsCommandBarTypeMenu, toolsMenuPopUp.CommandBar)); } return(commandBar); }
private void AddItemCommand(string name, string text, object bindings, int position, int faceId, bool beginGroup) { object[] contextGUIDS = new object[] { }; Commands2 commands = (Commands2)_applicationObject.Commands; CommandBars commandBars = ((CommandBars)_applicationObject.CommandBars); CommandBar[] targetBars = new CommandBar[] { commandBars["Folder"], commandBars["Project"] }; try { Command command = commands.AddNamedCommand2(_addInInstance, name, text, null, true, faceId, ref contextGUIDS, (int)vsCommandStatus.vsCommandStatusSupported + (int)vsCommandStatus.vsCommandStatusEnabled, (int)vsCommandStyle.vsCommandStylePictAndText, vsCommandControlType.vsCommandControlTypeButton); if (bindings != null) { command.Bindings = bindings; } if (command != null) { foreach (CommandBar bar in targetBars) { CommandBarButton button = (CommandBarButton)command.AddControl(bar, position); button.BeginGroup = beginGroup; } } } catch (ArgumentException) { } }
/// <summary> /// Initializes a new instance of the <see cref="VSMenuCommand"/> class. /// </summary> /// <param name="name">The name.</param> /// <param name="displayName">The display name.</param> /// <param name="description">The description.</param> public VSMenuCommand(VSMenu menu, string name, string displayName, string description) { _menu = menu; _name = name; _displayName = displayName; _description = description; object[] contextGUIDS = new object[] { }; Commands2 commands = (Commands2)menu.VSAddin.ApplicationObject.Commands; try { _command = commands.AddNamedCommand2(menu.VSAddin.AddInInstance, name, displayName, description, true, 0, ref contextGUIDS, (int)vsCommandStatus.vsCommandStatusSupported + (int)vsCommandStatus.vsCommandStatusEnabled, (int)vsCommandStyle.vsCommandStylePictAndText, vsCommandControlType.vsCommandControlTypeButton); } catch { // If we get here then the command name probably already exists. _command = commands.Item(menu.VSAddin.AddInInstance.ProgID + "." + name, 0); } _button = (CommandBarButton)_command.AddControl(_menu.Popup.CommandBar, 1); }
private bool CreateCommand() { try { Commands2 hCommands = m_hApplicationObject.Commands as Commands2; m_hCommand = hCommands.Item("CodeBeautifier.Connect." + m_strCommandName, 0); return(false); } catch (ArgumentException) { // Build command object[] contextGUIDS = new object[] { }; Commands2 hCommands = m_hApplicationObject.Commands as Commands2; m_hCommand = hCommands.AddNamedCommand2(m_hAddInInstance, (String)m_strCommandName, (String)m_strCommandCaption, (String)m_strCommandName, true, m_iIconIdx, contextGUIDS, (int)vsCommandStatus.vsCommandStatusSupported, (int)vsCommandStyle.vsCommandStylePictAndText, vsCommandControlType.vsCommandControlTypeButton); return(true); } }
/// <summary> /// 从菜单或工具条中删除指定的命令 /// </summary> /// <param name="CmdName"></param> /// <param name="SubItemName"></param> /// <param name="Name"></param> /// <param name="Caption"></param> /// <returns></returns> /// <remarks></remarks> public static Exception DeleteCommand(string CmdName, string SubItemName, string Name, string Caption) { //CmdName 工具条名称, SubItemName 工具条子项目名称,Name 要添加的项目名称, //Caption 要添加的项目标题.此方法内用于删除该按钮/项 Exception e = null; Commands2 Cmds = (Commands2)chDTE.Commands; CommandBars CmdBars = (CommandBars)chDTE.CommandBars; CommandBar mnuBarCmdBar = CmdBars[CmdName]; //菜单 CommandBarControl CmdCtrl = mnuBarCmdBar.Controls[SubItemName]; CommandBarPopup CmdPopup = (CommandBarPopup)CmdCtrl; try { Cmds.Item("KeelKit.Commands." + Name, 0).Delete(); } catch (Exception ex) { e = ex; } try { CommandBarControl chCmdConfig = CmdPopup.Controls[Caption]; chCmdConfig.Delete(null); } catch (Exception ex) { e = ex; } return(e); }
/// <summary> /// Deletes the command. /// </summary> /// <param name="commandName">Name of the command.</param> protected void DeleteCommand(string commandName) { TraceService.WriteLine("CommandManager::DeleteCommand commandName=" + commandName); try { Commands2 commands = (Commands2)this.VsInstance.ApplicationObject.Commands; CommandBarPopup toolsMenuPopUp = this.VsInstance.ApplicationObject.GetToolsMenuPopUp(); CommandBar commandBar = null; for (int i = 1; i <= toolsMenuPopUp.CommandBar.Controls.Count; i++) { if (toolsMenuPopUp.CommandBar.Controls[i].Caption == commandName) { TraceService.WriteLine("CommandManager::DeleteCommand commandFound in collection commandName=" + commandName); CommandBarPopup commandBarPopup = (CommandBarPopup)toolsMenuPopUp.CommandBar.Controls[i]; commandBar = commandBarPopup.CommandBar; break; } } if (commandBar != null) { TraceService.WriteLine("Command found and will be deleted ommandName=" + commandName); commandBar.Delete(); } } catch (Exception exception) { TraceService.WriteError("exception=" + exception.Message); TraceService.WriteError("stackTrace=" + exception.StackTrace); } }
/// <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; Command command = null; try { command = commands.AddNamedCommand2( _addInInstance, "CSVSAddInToolboxItem", "CSVSAddInToolboxItem", "Add item into VS Toolbox", true, 6743, ref contextGUIDS, (int)vsCommandStatus.vsCommandStatusSupported + (int)vsCommandStatus.vsCommandStatusEnabled, (int)vsCommandStyle.vsCommandStylePictAndText, vsCommandControlType.vsCommandControlTypeButton); } 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. } AddCommandToToolMenubar(_applicationObject, command); } }
private void CreateMenuItems() { object[] contextGUIDS = new object[] { }; Commands2 commands = (Commands2)_applicationObject.Commands; string toolsMenuName = "Tools"; //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, "Sync", "Sync Quick Test with Code", "Executes the command for QuickTestVS", true, 59, ref contextGUIDS, (int)vsCommandStatus.vsCommandStatusSupported | (int)vsCommandStatus.vsCommandStatusEnabled, (int)vsCommandStyle.vsCommandStylePictAndText, vsCommandControlType.vsCommandControlTypeButton); //Add a control for the command to the tools menu: if ((command != null) && (toolsPopup != null)) { var button = command.AddControl(toolsPopup.CommandBar, 2) as CommandBarButton; button.BeginGroup = true; } } 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. } }
bool ExecuteCommand(string command) { try { // Get an instance of the currently running Visual Studio IDE. DTE2 dte2; dte2 = Package.GetGlobalService(typeof(DTE)) as DTE2; // 2 checks to make sure the command exists in the IDE. Commands2 commands = (Commands2)(dte2.Commands); if (commands == null) { return(false); } Command dte_command = commands.Item(command, 0); if (dte_command == null) { return(false); } dte2.ExecuteCommand(command); return(dte_command.IsAvailable); } catch (Exception ex) { if (ex.HResult != -2147467259) { System.Windows.Forms.MessageBox.Show(ex.Message); } return(false); } }
/// <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; //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, "LastTab", "Reopen closed tab", "Opens the file that was most recently closed", true, 59, ref contextGUIDS, (int)vsCommandStatus.vsCommandStatusSupported + (int)vsCommandStatus.vsCommandStatusEnabled, (int)vsCommandStyle.vsCommandStylePictAndText, vsCommandControlType.vsCommandControlTypeButton); if (command != null) { command.Bindings = new object[2] { "Global::Ctrl+Shift+T", "Text Editor::Ctrl+Shift+T" }; } } 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. } } }
public async Task LoadTestAsync(string guidString, bool expectedSuccess) { //Arrange await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); IVsShell7 shell = (IVsShell7)ServiceProvider.GlobalProvider.GetService(typeof(SVsShell)); await UnitTestUtility.LoadPackageAsync(); VsServiceProvider.TryGetService(typeof(DTE), out object dteService); //Act var dte = dteService as DTE; Commands2 commands = dte.Commands as Commands2; Assumes.Present(shell); var guid = Guid.Parse(guidString); //Assert if (expectedSuccess) { await shell.LoadPackageAsync(ref guid); } else { await Assert.ThrowsAnyAsync <Exception>(async() => await shell.LoadPackageAsync(ref guid)); } }
private Command GetNewCommandAddedToDTECommands2(Commands2 commands, object[] contextGUIDS) { return (commands.AddNamedCommand2(addIn, TOOLS_COMMAND_NAME, RECORDER_ADD_IN_TOOLS_MENU_ITEM_NAME, TOOLS_COMMAND_DESCRIPTION, true, null, ref contextGUIDS, (int)vsCommandStatus.vsCommandStatusSupported + (int)vsCommandStatus.vsCommandStatusEnabled, (int)vsCommandStyle.vsCommandStyleText, vsCommandControlType.vsCommandControlTypeButton)); }
public command_manager(SsmsAbstract ssms) { _SSMS_commands_collection = (Commands2)VSI.ServiceCache.ExtensibilityModel.Commands; _addin_menu_commands_dictonary = new System.Collections.Generic.Dictionary <string, menu_command_handlers>(); _ssms = ssms; _addin_command_bars = new System.Collections.Generic.List <BARS.CommandBar>(); }
/// <summary>Реализация метода OnConnection интерфейса IDTExtensibility2. Получение уведомления о загрузке надстройки.</summary> /// <param term='Application'>Корневой объект ведущего приложения.</param> /// <param term='ConnectMode'>Описание способа загрузки надстройки.</param> /// <param term='AddInInst'>Объект, представляющий данную надстройку.</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; try { CommandBar menuBarCommandBar; CommandBarControl toolsControl; CommandBarPopup toolsPopup; CommandBarControl commandBarControl; //Добавление команды в коллекцию Commands: Command command = commands.AddNamedCommand2(addInInstance, "PasteXmlAsLinq", "Paste XML as XElement", "Pastes the XML on the clipboard as C# Linq To Xml code", true, 59, ref contextGUIDS, (int)vsCommandStatus.vsCommandStatusSupported + (int)vsCommandStatus.vsCommandStatusEnabled, (int)vsCommandStyle.vsCommandStylePictAndText, vsCommandControlType.vsCommandControlTypeButton); String editMenuName; //Поиск панели команд верхнего уровня MenuBar, в которой содержатся все элементы главного меню: menuBarCommandBar = ((CommandBars)applicationObject.CommandBars)["MenuBar"]; try { // С помощью этого кода можно получить региональный язык и региональные параметры, добавить имя элемента меню, // а затем добавить команду в меню. Список всех меню верхнего уровня можно найти в файле // CommandBar.resx. System.Resources.ResourceManager resourceManager = new System.Resources.ResourceManager("PasteXmlAsLinq.CommandBar", System.Reflection.Assembly.GetExecutingAssembly()); System.Threading.Thread thread = System.Threading.Thread.CurrentThread; System.Globalization.CultureInfo cultureInfo = thread.CurrentUICulture; editMenuName = resourceManager.GetString(String.Concat(cultureInfo.TwoLetterISOLanguageName, "Edit")); toolsControl = menuBarCommandBar.Controls["Edit"]; } catch (Exception) { // Мы пытаемся найти локализованную версию слова Edit, но безуспешно. // По умолчанию текст установлен в формат en-US, для используемого языка и региональных параметров этот вариант может оказаться приемлемым. toolsControl = menuBarCommandBar.Controls["Edit"]; } //Размещение команды в меню редактирования. toolsPopup = (CommandBarPopup)toolsControl; int pasteControlIndex = 1; //Поиск элемента управления вставкой для добавления после него нового элемента. foreach (CommandBarControl commandBar in toolsPopup.CommandBar.Controls) { if (String.Compare(commandBar.Caption, "&Paste", StringComparison.OrdinalIgnoreCase) == 0) { pasteControlIndex = commandBar.Index + 1; break; } } //Поиск подходящей панели команд на панели MenuBar: commandBarControl = (CommandBarControl)command.AddControl(toolsPopup.CommandBar, pasteControlIndex); } catch (Exception) { } } }
public static void LoadMe(bool ispack) { if (isLoad) { return; } try { Common.chOutWin = Common.chDTE.ToolWindows.OutputWindow.OutputWindowPanes.Item("KeelKit"); } catch (Exception) { Common.chOutWin = Common.chDTE.ToolWindows.OutputWindow.OutputWindowPanes.Add("KeelKit"); } Common.ShowInfo("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@", true); Common.ShowInfo("@@@ KeelKit 2012 @@@", true); Common.ShowInfo("@@@ http://www.mysticboy.cn @@@", true); Common.ShowInfo("@@@ [email protected] @@@", true); Common.ShowInfo("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@", true); Common.ShowInfo("", true); if (ispack == false) { Common.chMenu = Common.GetMenuBar("KeelKit"); } else { Commands2 Cmds = (Commands2)Common.chDTE.Commands; Microsoft.VisualStudio.CommandBars.CommandBars CmdBars = (Microsoft.VisualStudio.CommandBars.CommandBars)Common.chDTE.CommandBars; Microsoft.VisualStudio.CommandBars.CommandBarControl mnu = CmdBars["MenuBar"].Controls["KeelKit"]; Common.chMenu = mnu; } Assembly asm = System.Reflection.Assembly.GetExecutingAssembly(); Type[] ts = asm.GetTypes(); foreach (Type var in ts) { if (var.FullName.StartsWith("KeelKit.Commands")) { ICommand i = (ICommand)Assembly.GetExecutingAssembly().CreateInstance(var.FullName); Common.asmCommands.Add(i); i = null; } } Common.asmCommands.Sort(new Comparison <ICommand>(ComparisonCmd)); foreach (var item in Common.asmCommands) { Exception ex = Common.AddCommand(Common.chMenu, item.GetType().Name, item.Title, item.IcoID); if (ex != null) { Common.ShowInfo("加载菜单时出现异常:" + ex.Message); } } Common.AddOpenFloderFoVS(); Common.AddCopyToHtmlForVS(); HandEvents.HandAllEvents(); isLoad = true; Common.ShowInfo("就绪"); }
public Command CreateCommand(string name, string title, string description, string HotKey, ExecuteDelegate executeMethod, StatusDelegate statusMethod) { object[] contextGUIDS = new object[] { }; Command result = null; string fullname = GetFullName(name); result = GetCommand(fullname); if (result == null) { Commands2 commands = (Commands2)ApplicationObject.Commands; result = commands.AddNamedCommand2( AddInInstance, name, title, description, true, 0, ref contextGUIDS, (int)vsCommandStatus.vsCommandStatusSupported + (int)vsCommandStatus.vsCommandStatusEnabled, (int)vsCommandStyle.vsCommandStylePictAndText, vsCommandControlType.vsCommandControlTypeButton); // *** If a hotkey was provided try to set it //result.Bindings = bindings; if (HotKey != null && HotKey != "") { object[] bindings = (object[])result.Bindings; if (bindings != null) { bindings = new object[1]; bindings[0] = (object)HotKey; try { result.Bindings = (object)bindings; } catch { // Do nothing } } } } if (!CommandList.ContainsKey(fullname)) { CommandHandle handle = new CommandHandle(); handle.CommandObject = result; handle.ExecuteMethod = executeMethod; handle.StatusMethod = statusMethod; CommandList.Add(fullname, handle); } return(result); }
public CommandController(AsyncPackage aAsyncPackage) { if (VsServiceProvider.TryGetService(typeof(DTE), out object dte)) { var dte2 = dte as DTE2; mCommand = dte2.Commands as Commands2; } }
public void OnConnection(object application, ext_ConnectMode connectMode, object addInInst, ref Array custom) { _addInInstance = (AddIn)addInInst; _applicationObject = (DTE2)_addInInstance.DTE; if (connectMode == ext_ConnectMode.ext_cm_UISetup || connectMode == ext_ConnectMode.ext_cm_Startup) { _SSMSHelper = new GenericVSHelper(_applicationObject.RegistryRoot.StartsWith(@"Software\Microsoft\VisualStudio"), new GenericVSHelper.GetTextEditorKeyBindingScopeName(GetTextEditorKeyBindingScopeName), new GenericVSHelper.GetKeyBinding(GetFormatCommandKeyBinding), new GenericVSHelper.SetKeyBinding(SetFormatCommandKeyBinding)); object [] contextGUIDS = new object[] { }; Commands2 commandsList = (Commands2)_applicationObject.Commands; CommandBarPopup targetPopup = GetMainMenuPopup("Tools"); //remove old commands List <string> oldCommandNames = new List <string>(); oldCommandNames.Add("PoorMansTSqlFormatterSSMSAddIn.Connect.PoorMansTSqlFormatterSSMSAddIn"); oldCommandNames.Add("PoorMansTSqlFormatterSSMSAddIn.AddinConnector.FormatSelectionOrActiveWindow"); oldCommandNames.Add("PoorMansTSqlFormatterSSMSAddIn.AddinConnector.FormattingOptions"); RemoveCommands(commandsList, oldCommandNames); //add new commands Command formatCommand = commandsList.AddNamedCommand2( _addInInstance, "FormatSelectionOrActiveWindow", _SSMSHelper.GeneralResourceManager.GetString("FormatButtonText"), _SSMSHelper.GeneralResourceManager.GetString("FormatButtonToolTip"), true, 59, ref contextGUIDS, (int)vsCommandStatus.vsCommandStatusSupported + (int)vsCommandStatus.vsCommandStatusEnabled, (int)vsCommandStyle.vsCommandStyleText, vsCommandControlType.vsCommandControlTypeButton ); if ((formatCommand != null) && (targetPopup != null)) { formatCommand.AddControl(targetPopup.CommandBar, 1); } _formatCommand = formatCommand; _SSMSHelper.UpdateSettingsHotkeyIntoVS(); Command optionsCommand = commandsList.AddNamedCommand2( _addInInstance, "FormattingOptions", _SSMSHelper.GeneralResourceManager.GetString("OptionsButtonText"), _SSMSHelper.GeneralResourceManager.GetString("OptionsButtonToolTip"), true, 59, ref contextGUIDS, (int)vsCommandStatus.vsCommandStatusSupported + (int)vsCommandStatus.vsCommandStatusEnabled, (int)vsCommandStyle.vsCommandStyleText, vsCommandControlType.vsCommandControlTypeButton ); if ((optionsCommand != null) && (targetPopup != null)) { optionsCommand.AddControl(targetPopup.CommandBar, 2); } } }
internal command_manager(SSMS ssms) { // VSI.ServiceCache.ExtensibilityModel.Commands was NULL when called. // _SSMS_commands_collection = (Commands2)VSI.ServiceCache.ExtensibilityModel.Commands; _SSMS_commands_collection = (Commands2)ssms.addin.DTE.Commands; _addin_menu_commands_dictonary = new System.Collections.Generic.Dictionary <string, menu_command_handlers>(); _ssms = ssms; _addin_command_bars = new System.Collections.Generic.List <BARS.CommandBar>(); }
internal command_manager(SSMS ssms) { // VSI.ServiceCache.ExtensibilityModel.Commands was NULL when called. // _SSMS_commands_collection = (Commands2)VSI.ServiceCache.ExtensibilityModel.Commands; _SSMS_commands_collection = (Commands2)ssms.addin.DTE.Commands; _addin_menu_commands_dictonary = new System.Collections.Generic.Dictionary<string, menu_command_handlers>(); _ssms = ssms; _addin_command_bars = new System.Collections.Generic.List<BARS.CommandBar>(); }
/// <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; _textDocKeyEvents = ((Events2) _applicationObject.Events).get_TextDocumentKeyPressEvents(); _commands = (Commands2) _applicationObject.Commands; try { _commands.AddNamedCommand2(_addInInstance, "Toggle", "Toggle TestCase", "Toggle test naming replacements on or off", false); } catch (Exception) { } _textDocKeyEvents.BeforeKeyPress += new _dispTextDocumentKeyPressEvents_BeforeKeyPressEventHandler(BeforeKeyPress); }
public object[] AddCommandBarToToolsMenu(AddIn addInInstance, DTE2 applicationObject, Commands2 commands, object[] contextGUIDS, CommandBars commandBars) { Command command = commands.AddNamedCommand2( addInInstance, "WsContractFirst", "Web Services Contract-First...", "Executes the command for WsContractFirstAddin", true, 190, ref contextGUIDS, (int)vsCommandStatus.vsCommandStatusUnsupported + (int)vsCommandStatus.vsCommandStatusEnabled, (int)vsCommandStyle.vsCommandStylePictAndText, vsCommandControlType.vsCommandControlTypeButton); command.AddControl(toolsSubMenuCommandBar, 1); AppLog.LogMessage("Command bar is added to the Tools menu."); return contextGUIDS; }
private void RegisterSimpleCommand(Commands2 commands, string name, string buttonText, string bindings) { object[] contextGUIDS = new object[] { }; Command cmd = commands.AddNamedCommand2(_addInInstance, name, buttonText, string.Empty, true, 59, ref contextGUIDS, (int)vsCommandStatus.vsCommandStatusSupported + (int)vsCommandStatus.vsCommandStatusEnabled, (int)vsCommandStyle.vsCommandStylePictAndText, vsCommandControlType.vsCommandControlTypeButton); if (bindings != null) cmd.Bindings = bindings; }
/// <summary> /// Adds new command to the specified command collection. /// </summary> private Command CreateCommand(AddIn addInInstance, Commands2 commands) { return commands.AddNamedCommand2( addInInstance, CommandName, CommandText, CommandTooltip, false, IconBitmapCode); }
/// <summary> /// Tries to find current command in specified command collection. /// </summary> private Command FindCommand(Commands2 commands) { for (int i = commands.Count; i >= 1; i--) { Command command = commands.Item(i); if (command.Name == FullCommandName) { return command; } } return null; }
public CommandCollectionPathNodeFactory(Commands2 commands) { _commands = commands; }
private Command GetCommand(string commandName, string caption, string tooltip, int iconIndex, vsCommandStyle commandStyle, Commands2 commands) { var contextGUIDS = new object[] {}; // Add command Command command = GetCommand(commandName); if (_visualStudioCommands.ContainsKey(commandName)) return command; if (command == null && iconIndex > 0) { try { command = commands.AddNamedCommand2(_addIn, commandName, caption, tooltip, false, iconIndex, ref contextGUIDS, (int) vsCommandStatus.vsCommandStatusSupported | (int) vsCommandStatus.vsCommandStatusEnabled, (int) commandStyle, vsCommandControlType.vsCommandControlTypeButton); } catch (Exception) { } } if (command == null && commandStyle != vsCommandStyle.vsCommandStylePict) { command = commands.AddNamedCommand2(_addIn, commandName, caption, tooltip, true, -1, ref contextGUIDS, (int) vsCommandStatus.vsCommandStatusSupported + (int) vsCommandStatus.vsCommandStatusEnabled, (int) commandStyle, vsCommandControlType.vsCommandControlTypeButton); } if (command != null) { _visualStudioCommands[commandName] = command; } return command; }
private static void AddCommand(Commands2 c, AddIn a, object[] o, string name, string display, string tip) { c.AddNamedCommand2(a, name, display, tip, true, 59, ref o, StatusSupported + StatusEnabled, StyleText); }
private void _DeleteIndividualCommand(Commands2 cmds, String fullCommandName) { try { Command cmdToDelete = cmds.Item(fullCommandName, -1); cmdToDelete.Delete(); } catch (ArgumentException) { // The ArgumentException will be thrown if the command does not // exist. It is fine to eat this exception as that means it's // the first run of this add in. } }
private static void RemoveCommands(Commands2 commandsList, List<string> oldCommandNames) { List<Command> oldCommands = new List<Command>(); foreach (Command candidate in commandsList) if (oldCommandNames.Contains(candidate.Name)) oldCommands.Add(candidate); foreach (Command oldEntry in oldCommands) oldEntry.Delete(); }
private void AddCommandToMenu(string toolsMenuName, Commands2 commands, object[] contextGUIDS) { CommandBar menuCommandBar = GetMenuCommandBar(); CommandBarPopup toolsPopup = GetToolsPopup(menuCommandBar, toolsMenuName); try { Command command = GetNewCommandAddedToDTECommands2(commands, contextGUIDS); AddControlToToolsMenu(command, toolsPopup); } catch (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. } }
private CommandBarButton GetOrCreateCommandBarButton(CommandBar commandBar, Command command, Commands2 commands) { foreach (CommandBarControl control in commandBar.Controls) { CommandBarButton button = control as CommandBarButton; if (button != null) { string guid; int id; commands.CommandInfo(control, out guid, out id); if (command.Guid == guid) return button; } } return (CommandBarButton)command.AddControl(commandBar, 1); }
private Command getCommand(Commands2 commands, string commandName) { foreach (Command cmd in commands) if (cmd.Name.EndsWith("." + commandName)) return cmd; return null; }
private void Initialise(object instance) { _addIn = (EnvDTE.AddIn)instance; Application = ((EnvDTE.AddIn)instance).DTE; _commands = (Commands2)Application.Commands; }
private Command CmdIsCreated(string cmdname, Commands2 commands) { foreach (Command cmd in commands) { if (cmd.Name.Equals(cmdname)) { return cmd; } } return null; }
public object[] GenerateMenuItemForWSCodeGen(AddIn addInInstance, DTE2 applicationObject, Commands2 commands, object[] contextGUIDS) { Command cmdObj = commands.AddNamedCommand2( addInInstance, "WsContractFirstContextMenu", "Generate Web Service Code...", "Executes the command for WsContractFirstAddin ContextMenu", true, 190, ref contextGUIDS, (int)vsCommandStatus.vsCommandStatusUnsupported + (int)vsCommandStatus.vsCommandStatusEnabled, (int)vsCommandStyle.vsCommandStylePictAndText, vsCommandControlType.vsCommandControlTypeButton); cmdObj.AddControl(subMenuCommandBar, 1); // BDS 11/21/2005: Add this menu item to the web project // template. cmdObj.AddControl(webSubMenuCommandBar, 1); AppLog.LogMessage("Generate Web Serive Code menu item is added."); return contextGUIDS; }
public void OnConnection(object application, ext_ConnectMode connectMode, object addInInst, ref Array custom) { if (connectMode == ext_ConnectMode.ext_cm_Startup) { _app = (DTE2)application; _addIn = (AddIn)addInInst; CommandBarPopup depMainPop = null; cmdHt = new Hashtable(); commands = (Commands2)_app.Commands; solevt = _app.Events.SolutionEvents; solevt.AfterClosing += new _dispSolutionEvents_AfterClosingEventHandler(solevt_AfterClosing); solevt.ProjectAdded += new _dispSolutionEvents_ProjectAddedEventHandler(solevt_ProjectAdded); solevt.Opened += new _dispSolutionEvents_OpenedEventHandler(solevt_Opened); Hashtable ht = new Hashtable(); foreach (Command c in commands) { if (c.Name.Contains("DeployAddIn")) cmdHt.Add(c.Name, c); } object[] contextGUIDS = new object[] { }; string toolsMenuName; try { ResourceManager resourceManager = new ResourceManager("DeployAddIn.CommandBar", Assembly.GetExecutingAssembly()); CultureInfo cultureInfo = new System.Globalization.CultureInfo(_app.LocaleID); string resourceName = String.Concat(cultureInfo.TwoLetterISOLanguageName, "Tools"); 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 = "Tools"; } //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 menuBar = ((Microsoft.VisualStudio.CommandBars.CommandBars)_app.CommandBars)["MenuBar"]; //Find the Tools command bar on the MenuBar command bar: CommandBarControl toolsControl = menuBar.Controls[toolsMenuName]; CommandBarPopup toolsPopup = (CommandBarPopup)toolsControl; try { depMainPop = (CommandBarPopup)toolsPopup.Controls.Add(vsCommandBarType.vsCommandBarTypePopup, 1, "", 1, true); depMainPop.Caption = "SQL CLR Deployment"; depMainPop.BeginGroup = true; depMainPop.Visible = true; //Add a command to the Commands collection: AddCmd(depMainPop.CommandBar, "DepProp", "Deployment Properties", "Allows you to set properties for the deployment task.", 1); } catch (Exception ex1) { MessageBox.Show(ex1.Message, "Error"); } try { CommandBarPopup depSubPop = (CommandBarPopup)depMainPop.Controls.Add(vsCommandBarType.vsCommandBarTypePopup, 1, "", 2, true); depSubPop.Caption = "Deploy/Drop Assemblies"; depSubPop.BeginGroup = true; depSubPop.Visible = true; AddCmd(depSubPop.CommandBar, "DepAll", "Deploy All (assembly, methods etc)", "Deploys the assembly and all the procedures, functions etc.", 1); AddCmd(depSubPop.CommandBar, "DepAsm", "Deploy Assembly", "Deploys the assembly.", 2); AddCmd(depSubPop.CommandBar, "DepUdt", "Create UDT's", "Creates the user defined types in the assembly.", 3); AddCmd(depSubPop.CommandBar, "DepMeth", "Create Methods", "Creates the procedures, functions etc, in the assembly", 4); AddCmd(depSubPop.CommandBar, "DropAll", "Drop All (assembly, methods etc)", "Drops the assembly and all the procedures, functions etc.", 5); AddCmd(depMainPop.CommandBar, "Debug", "Debug", "Debug the assembly.", 3); } catch (Exception ex2) { MessageBox.Show(ex2.Message, "Error"); } } }
private Command _AddIndividualCommand(Commands2 cmds, vsCommandStatus statusValue, ICommand c) { object[] contextGUIDS = new object[] { }; vsCommandStyle style = vsCommandStyle.vsCommandStylePict; String buttonText = c.CommandText; String toolTip = c.CommandText; Command command = cmds.AddNamedCommand2(_addInInstance , c.CommandText , buttonText , toolTip , false , null , ref contextGUIDS , (int)statusValue , (int)style , vsCommandControlType.vsCommandControlTypeButton ); return command; }
private Command GetNewCommandAddedToDTECommands2(Commands2 commands, object[] contextGUIDS) { return commands.AddNamedCommand2(addIn, TOOLS_COMMAND_NAME, RECORDER_ADD_IN_TOOLS_MENU_ITEM_NAME, TOOLS_COMMAND_DESCRIPTION, true, null, ref contextGUIDS, (int) vsCommandStatus.vsCommandStatusSupported + (int) vsCommandStatus.vsCommandStatusEnabled, (int) vsCommandStyle.vsCommandStyleText, vsCommandControlType.vsCommandControlTypeButton); }
private void AddCommandsForClassGenerator(Commands2 commands, object[] contextGUIDS) { AddCommandToMenu(GetLocalizedVersionOfToolsMenuName(), commands, contextGUIDS); AddCommandToContextMenu(contextGUIDS, CLASS_GEN_CONTEXT_MENU_CMD_NAME, CLASS_GEN_CONTEXT_MENU_NAME, CLASS_GEN_CONTEXT_MENU_CMD_DESCIPTION, PROJECT_COMMAND_BAR); }
public void GenerateMenuItemForPasteXmlAsSchema(AddIn addInInstance, DTE2 applicationObject, Commands2 commands, CommandBars commandBars, object[] contextGUIDS) { Command cmdObj = commands.AddNamedCommand2( addInInstance, "PasteSchemaMenu", "Paste XML as Schema", "Pastes the XML on the clipboard as XSD schema.", true, 239, ref contextGUIDS, (int)vsCommandStatus.vsCommandStatusSupported + (int)vsCommandStatus.vsCommandStatusEnabled, (int)vsCommandStyle.vsCommandStylePictAndText, vsCommandControlType.vsCommandControlTypeButton); CommandBar menuBarCommandBar = commandBars["MenuBar"]; CommandBarControl editControl = menuBarCommandBar.Controls["Edit"]; CommandBarPopup editPopup = (CommandBarPopup)editControl; CommandBarControl pasteControl = editPopup.CommandBar.Controls["Paste"]; cmdObj.AddControl(editPopup.CommandBar, pasteControl != null ? pasteControl.Index + 1 : 1); AppLog.LogMessage("Paste Schema code menu item is added"); }