DTE: attempt to cast ProjectItem's Window.Document to a TextDocument throws exception

StackOverflow https://stackoverflow.com/questions/17003414

  •  31-05-2022
  •  | 
  •  

Question

Carlos J. Quintero seems to know a lot about DTE. In an article updated in March of this year and published on the Web (http://www.mztools.com/articles/2007/mz2007027.aspx) he says that the Open method on an EnvDTE. ProjectItem returns an EnvDTE.Window, whose Document property can be cast to an EnvDTE.TextDocument.

But when I try this, I get an exception (HRESULT: 0x80004002 [E_NOINTERFACE]). It seems that the __ComObject returned by Open doesn't know about TextDocument:

enter image description here

An (extracted and slightly edited) excerpt from my VB .Net code (VS2008 running under Windows 7 Pro 64 in WOW):

...handler for BuildEvents.OnBuildBegin recursively traverses all items in all projects; filters names to find those containing ".Designer.vb" (apparently works fine to here). For each found, want to replace certain text; to do so, need TextDocument object:

'the below returns __ComObject instead of EnvDTE.Window
Dim ItemWindow as EnvDTE.Window = ProjectItem.Open(EnvDTE.Constants.vsext_vk_Code) 
'the below throws exception
Dim ItemTextDocument as EnvDTE.TextDocument = CType(ItemWindow.Document, EnvDTE.TextDocument) 

complete error:

Unable to cast COM object of type 'System.__ComObject' to interface type 'EnvDTE.TextDocument'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{CB218890-1382-472B-9118-782700C88115}' failed due to the following error: Interface wordt niet ondersteund (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).

What is wrong? Any help appreciated.

Was it helpful?

Solution

I ran into the same problem

You can fix this by specifying what type of document you want to get from the window object

public static void SetCode(ProjectItem projectItem, string newCode)
{

    Window EditWindow = projectItem.Open(Constants.vsext_vk_Code);
    EditWindow.Visible = true; //hide editor window

    TextDocument TextDocument = (TextDocument)EditWindow.Document.Object("TextDocument");

    EditPoint EditPoint = TextDocument.StartPoint.CreateEditPoint();
    EditPoint.Delete(TextDocument.EndPoint); //delete content
    EditPoint.Insert(newCode);

    EditWindow.Close(vsSaveChanges.vsSaveChangesYes);
}

you'll have to convert that back to VB.NET yourself

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top