Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find an IVsTextView or IWpfTextView for a given ProjectItem, in VS 2010 RC extension

I have the ProjectItem, and want to get the IWPFTextView that is associated with it, if any.

I have tried to get an IVsTextManager, and then iterate through the views, but iVsTextManager.EnumViews always returns nothing.

Here is what I've got so far:

var txtMgr = (IVsTextManager)Package.GetGlobalService(typeof(SVsTextManager));

if (txtMgr != null)
{
    IVsEnumTextViews iVsEnumTextViews;
    IVsTextView[] views = null;

    // Passing null will return all available views, at least according to the documentation
    // unfortunately, this returns a 0x80070057 error (invalid parameter)
    var errorValue = txtMgr.EnumViews(null, out iVsEnumTextViews);

    if (errorValue == VSConstants.S_OK)
    {
        // enumerate, find the IVsTextView with a matching filename.

Surely there is another/better way??

Thanks in advance

~ Cameron

like image 618
Cameron Peters Avatar asked Mar 09 '10 23:03

Cameron Peters


1 Answers

Here is how to do it. First get the full path for the project item, then call this helper method:

/// <summary>
/// Returns an IVsTextView for the given file path, if the given file is open in Visual Studio.
/// </summary>
/// <param name="filePath">Full Path of the file you are looking for.</param>
/// <returns>The IVsTextView for this file, if it is open, null otherwise.</returns>
internal static Microsoft.VisualStudio.TextManager.Interop.IVsTextView GetIVsTextView(string filePath)
{
    var dte2 = (EnvDTE80.DTE2)Microsoft.VisualStudio.Shell.Package.GetGlobalService(typeof(Microsoft.VisualStudio.Shell.Interop.SDTE));
    Microsoft.VisualStudio.OLE.Interop.IServiceProvider sp = (Microsoft.VisualStudio.OLE.Interop.IServiceProvider)dte2;
    Microsoft.VisualStudio.Shell.ServiceProvider serviceProvider = new Microsoft.VisualStudio.Shell.ServiceProvider(sp);

    Microsoft.VisualStudio.Shell.Interop.IVsUIHierarchy uiHierarchy;
    uint itemID;
    Microsoft.VisualStudio.Shell.Interop.IVsWindowFrame windowFrame;
    Microsoft.VisualStudio.Text.Editor.IWpfTextView wpfTextView = null;
    if (Microsoft.VisualStudio.Shell.VsShellUtilities.IsDocumentOpen(serviceProvider, filePath, Guid.Empty,
                                    out uiHierarchy, out itemID, out windowFrame))
    {
        // Get the IVsTextView from the windowFrame.
        return Microsoft.VisualStudio.Shell.VsShellUtilities.GetTextView(windowFrame);
    }

    return null;
}
like image 195
Cameron Peters Avatar answered Sep 22 '22 05:09

Cameron Peters