Я хочу добавить новую опцию в контекстном меню проводника решения 2010-х Visual Studio для определенного типа файла. Так, например, щелчок правой кнопкой по *.cs файлу покажет существующее контекстное меню плюс "моя новая опция".
Я задаюсь вопросом, на что был бы похож код; и любил бы указатель на хорошую ссылку для разработки плагинов Visual Studio. Учебные руководства/ссылки, которые я вижу, заметно неприятны.
Спасибо!
На это у меня ушло около 5 часов.
Есть 2 варианта: надстройка Visual Studio (или общая надстройка) и пакет Visual Studio.
Пакет намного сложнее, чтобы дать вам гораздо больше контроля, но для контекстного меню в обозревателе решений он не нужен.
Итак, новый проект -> Другие типы проектов -> Расширяемость -> Надстройка Visual Studio.
Вот пошаговое руководство - Ссылка
Также Я следил за некоторыми - Ссылка
Я рекомендую вам оставить опцию для добавления в меню инструментов, пока у вас не заработает контекстное меню, или предоставить место для размещения диалогового окна настроек (если вы не пишете страницу Tool-> options.
Вот код подключения:
_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";
//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;
// get popUp command bars where commands will be registered.
CommandBars cmdBars = (CommandBars)(_applicationObject.CommandBars);
CommandBar vsBarItem = cmdBars["Item"]; //the pop up for clicking a project Item
CommandBar vsBarWebItem = cmdBars["Web Item"];
CommandBar vsBarMultiItem = cmdBars["Cross Project Multi Item"];
CommandBar vsBarFolder = cmdBars["Folder"];
CommandBar vsBarWebFolder = cmdBars["Web Folder"];
CommandBar vsBarProject = cmdBars["Project"]; //the popUpMenu for right clicking a project
CommandBar vsBarProjectNode = cmdBars["Project Node"];
//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, "HintPaths", "HintPaths", "Executes the command for HintPaths", 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))
{
//command.AddControl(toolsPopup.CommandBar, 1);
command.AddControl(vsBarProject);
}
}
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.
}
}
}
Этот код проверяет, является ли то, что выбрал пользователь, проектом для instance:
private Project GetProject()
{
if (_applicationObject.Solution == null || _applicationObject.Solution.Projects == null || _applicationObject.Solution.Projects.Count < 1)
return null;
if (_applicationObject.SelectedItems.Count == 1 && _applicationObject.SelectedItems.Item(1).Project != null)
return _applicationObject.SelectedItems.Item(1).Project;
return null;
}
Обратите внимание, что некоторые имена строк в вашем коде должны совпадать, и я еще не уверен, какие именно, поскольку я только что сделал это вчера.
UPDATE:
GAX/GAT для VS2010 также доступен с http://msdn.microsoft.com/en-us/library/ff687173
ORIGINAL POST
Ну это ужасно, потому что VS действительно сложная. Использование GAX/GAT было возможно, но пока нет версии VS2010. Я предлагаю скачать несколько примеров из Visual Studio Gallery, чтобы попытаться понять, как все это работает, к сожалению, это нелегкая задача.
HTH
Я обнаружил, что лучше всего было бы создать пакет Visual Studio вместо надстройки Visual Studio. Развертывание vsix очень приятное - все было очень легко. Он поддерживает только Visual Studio 2010, но в моем случае этого было достаточно.
Вот результат vsct:
<Commands package="guidBingfooPluginPkg">
<Groups>
<Group guid="guidBingfooPluginCmdSet" id="MyMenuGroup" priority="0x0600">
<Parent guid="guidSHLMainMenu" id="IDM_VS_CTXT_ITEMNODE"/>
</Group>
</Groups>
<Buttons>
<Button guid="guidBingfooPluginCmdSet" id="cmdidfooLocalBox" priority="0x0100" type="Button">
<Parent guid="guidBingfooPluginCmdSet" id="MyMenuGroup" />
<!-- <Icon guid="guidImages" id="bmpPic1" /> -->
<CommandFlag>DynamicVisibility</CommandFlag>
<Strings>
<CommandName>cmdidfooLocalBox</CommandName>
<ButtonText>View in foo</ButtonText>
</Strings>
</Button>
<Button guid="guidBingfooPluginCmdSet" id="cmdidfooTestBed" priority="0x0100" type="Button">
<Parent guid="guidBingfooPluginCmdSet" id="MyMenuGroup" />
<CommandFlag>DynamicVisibility</CommandFlag>
<Strings>
<CommandName>cmdidfooTestBed</CommandName>
<ButtonText>View in foo on Test Beds</ButtonText>
</Strings>
</Button>
</Buttons>
<Bitmaps>
<Bitmap guid="guidImages" href="Resources\Images_32bit.bmp" usedList="bmpPic1, bmpPic2, bmpPicSearch, bmpPicX, bmpPicArrows"/>
</Bitmaps>
</Commands>
<Symbols>
<GuidSymbol name="guidBingfooPluginPkg" value="{62c4a13c-cc61-44a0-9e47-33111bd323ce}" />
<GuidSymbol name="guidBingfooPluginCmdSet" value="{59166210-d88c-4259-9809-418bc332b0ab}">
<IDSymbol name="MyMenuGroup" value="0x1020" />
<IDSymbol name="cmdidfooLocalBox" value="0x0100" />
<IDSymbol name="cmdidfooTestBed" value="0x0101" />
</GuidSymbol>
<GuidSymbol name="guidImages" value="{2dff8307-a49a-4951-a236-82e047385960}" >
<IDSymbol name="bmpPic1" value="1" />
<IDSymbol name="bmpPic2" value="2" />
<IDSymbol name="bmpPicSearch" value="3" />
<IDSymbol name="bmpPicX" value="4" />
<IDSymbol name="bmpPicArrows" value="5" />
</GuidSymbol>
</Symbols>
</CommandTable>