コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【Visual Studio 拡張機能作成】ソリューションエクスプローラで項目を右クリックした時に表示されるコンテキストメニューに「このアイテムのフォルダーを開く」を追加する拡張機能

検証環境

  • Visual Studio 2017

概要

private void MenuItemCallback( object sender, EventArgs e )
{
    Object selectedObject = null;

    var monitorSelection = Package.GetGlobalService( typeof( SVsShellMonitorSelection ) ) as IVsMonitorSelection;

    monitorSelection.GetCurrentSelection
    (
        out IntPtr hierarchyPointer,
        out uint projectItemId,
        out IVsMultiItemSelect multiItemSelect,
        out IntPtr selectionContainerPointer
    );

    if ( Marshal.GetTypedObjectForIUnknown( hierarchyPointer, typeof( IVsHierarchy ) ) is IVsHierarchy selectedHierarchy )
    {
        ErrorHandler.ThrowOnFailure
        (
            selectedHierarchy.GetProperty
            (
                projectItemId,
                ( int )__VSHPROPID.VSHPROPID_ExtObject,
                out selectedObject
            )
        );
    }

    var selectedProjectItem = selectedObject as ProjectItem;
    var fullPath = selectedProjectItem.Properties.Item( "FullPath" ).Value.ToString();
    var isDirectory = File.GetAttributes( fullPath ).HasFlag( FileAttributes.Directory );
    var directoryName = Path.GetDirectoryName( fullPath );
    var target = isDirectory
        ? directoryName.Substring( 0, directoryName.LastIndexOf( @"\" ) + 1 )
        : directoryName
    ;

    System.Diagnostics.Process.Start( target );
}

カスタムコマンドで MenuCommand クラスに設定するコールバックに
上記のコードを記述します

<Groups>
  <Group guid="guidCommand1PackageCmdSet" id="MyMenuGroup" priority="0x0600">
    <Parent guid="guidSHLMainMenu" id="IDM_VS_CTXT_ITEMNODE"/>
  </Group>
  <Group guid="guidCommand1PackageCmdSet" id="MyMenuGroup" priority="0x0600">
    <Parent guid="guidSHLMainMenu" id="IDM_VS_CTXT_FOLDERNODE"/>
  </Group>
</Groups>
<Buttons>
  <Button guid="guidCommand1PackageCmdSet" id="Command1Id" priority="0x0100" type="Button">
    <Parent guid="guidCommand1PackageCmdSet" id="MyMenuGroup" />
    <Strings>
      <ButtonText>このアイテムのフォルダーを開く</ButtonText>
    </Strings>
  </Button>
</Buttons>

そして、.vsct ファイルの「Groups」と「Buttons」を上記のように設定します

f:id:baba_s:20171206193949p:plain

これで、ソリューションエクスプローラで項目を右クリックした時に表示される
コンテキストメニューに「このアイテムのフォルダーを開く」が追加されて、
これを選択すると、そのファイルが格納されているフォルダがエクスプトーラで開きます