0

我正在開發一個Visual Studio擴展,其中我將元素添加到項目中引用的右鍵單擊(上下文)菜單。這是通過定義與IDM_VS_CTXT_REFERENCE的父母Group完成的。找出在Visual Studio擴展中點擊了哪個引用

我想表明,隱藏這取決於被點擊的參考菜單元素,所以我定義我的菜單項爲OleMenuCommand

if (commandService != null) 
{ 
    var menuCommandID = new CommandID(CommandSet, CommandId); 
    var menuItem = new OleMenuCommand(this.MenuItemCallback, menuCommandID); 

    menuItem.BeforeQueryStatus += (sender, args) => 
    { 
     var button = (OleMenuCommand)sender; 
     button.Visible = this.CommandVisible(); 
    }; 

    commandService.AddCommand(menuItem); 
} 

我實現CommandVisible方法麻煩。比方說,如果參考名稱以A開頭,我想要顯示菜單。我會怎麼做?

我覺得自己被困在interop地獄裏,瞎猜在任意的id,guids和不存在/不可理解的文檔上。

我已成功地挖掘出項目我的引用是爲IVsProject有的ID爲參考,但調用GetMkDocument回報什麼(它的工作原理與項目文件,但不引用)。

我該怎麼做?我在哪裏可以找到關於如何做到這一點的文檔?

+0

GetMkDocument只適用於實際的文檔,引用只是一種視覺援助,實際上不是文件。我正在進行一些測試,看看我能否幫助你。 –

+0

工作出現了,但我把它拿到了盡頭,關鍵是要使用使用itemid的IVsHierarchy方法。我認爲你在正確的軌道上。 –

回答

3

終於明白了。一旦你有了所選項目的IVsHierarchy和itemid,這行就會在你的參數中得到你想要的名字。

hierarchy.GetProperty(itemid, (int)__VSHPROPID.VSHPROPID_Name, out name); 

全碼

object name; 
uint itemid = VSConstants.VSITEMID_NIL; 
IVsMultiItemSelect multiItemSelect = null; 
IntPtr hierarchyPtr = IntPtr.Zero; 
IntPtr selectionContainerPtr = IntPtr.Zero; 
try 
{ 
    var monitorSelection = Package.GetGlobalService(typeof(SVsShellMonitorSelection)) as IVsMonitorSelection; 
    monitorSelection.GetCurrentSelection(out hierarchyPtr, out itemid, out multiItemSelect, out selectionContainerPtr); 
    hierarchy = Marshal.GetObjectForIUnknown(hierarchyPtr) as IVsHierarchy;  
    hierarchy.GetProperty(itemid, (int)__VSHPROPID.VSHPROPID_Name, out name); 
}finally 
{ 
    if (selectionContainerPtr != IntPtr.Zero) 
     Marshal.Release(selectionContainerPtr); 

     if (hierarchyPtr != IntPtr.Zero) 
      Marshal.Release(hierarchyPtr); 
} 
+0

一個重要的注意事項:你需要調用hierachyPtr變量上的Marshal.Release,否則你將泄漏COM引用,並且你有內存泄漏。 –

+0

是的你是正確的,代碼是其他代碼中的一個片段,所以我忘了包括它。更新。 –

+0

不要忘記使用finally塊,以防萬一中間有什麼東西拋出。 :-( –