Visual Studio Extension: Get the path of the current selected file in the Solution Explorer

泄露秘密 提交于 2019-12-10 18:55:31

问题


I'm trying to create my first extension for visual studio and so far I've been following this tutorial to get me started (http://www.diaryofaninja.com/blog/2014/02/18/who-said-building-visual-studio-extensions-was-hard). Now I have a custom menu item appearing when I click on a file in the solution explorer. What I need now for my small project is to get the path of the file selected in the solution explorer but I can't understand how can I do that. Any help?

---------------------------- EDIT ------------------------------

As matze said, the answer is in the link I posted. I just didn't notice it when I wrote it. In the meanwhile I also found another possible answer in this thread: How to get the details of the selected item in solution explorer using vs package

where I found this code:

foreach (UIHierarchyItem selItem in selectedItems)
            {
                ProjectItem prjItem = selItem.Object as ProjectItem;
                string filePath = prjItem.Properties.Item("FullPath").Value.ToString();
                //System.Windows.Forms.MessageBox.Show(selItem.Name + filePath);
                return filePath;
            }

So, here are two ways to get the path to the selected file(s) :)


回答1:


The article you mentioned already contains a solution for that.

Look for the menuCommand_BeforeQueryStatus method in the sample code. It uses the IsSingleProjectItemSelection method to obtain an IVsHierarchy object representing the project as well as the id of the selected item. It seems that you can safely cast the hierarchy to IVsProject and use it´s GetMkDocument function to query the item´s fullpath...

IVsHierarchy hierarchy = null;
uint itemid = VSConstants.VSITEMID_NIL;

if (IsSingleProjectItemSelection(out hierarchy, out itemid))
{
    IVsProject project;
    if ((project = hierarchy as IVsProject) != null)
    {
        string itemFullPath = null;
        project.GetMkDocument(itemid, out itemFullPath);
    }
}

I don´t want to copy the entire code from the article into this answer, but it might be of interest how the IsSingleProjectItemSelection function obtains the selected item; so I just add some notes instead which may guide into the right direction... The method uses the GetCurrentSelection method of the global IVsMonitorSelection service to query to the current selected item.



来源:https://stackoverflow.com/questions/34677290/visual-studio-extension-get-the-path-of-the-current-selected-file-in-the-soluti

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!