Question

When using the Visual Studio extensibility SDK I have an instance of a ProjectItem. I'm trying to get the text from this item so I can do some replacements on it. The way that I've seen this done is by using the properties on DTE2.ActiveDocument.Selection. However, the DTE2.ActiveDocument isn't the document that I need so I can't use that. When I try to access the ProjectItem.Document object which contains a Selection property the document is always null and I get a null reference exception. I've also tried the following which doesn't work (i.e. the Document is valid, but the Selection property is null):

Document document = null;
if (!projectItem.IsOpen)
    document = projectItem.Open().Document;

I tried the following but it didn't give me the correct document since the ProjectItem I'm dealing with isn't the active document. Is there any way to implement something similar to the following code that uses ProjectItem.Document instead?

TextSelection selection = DTE2.ActiveDocument.Selection;
selection.SelectAll();
string text = selection.Text;
selection.Delete();
//Do replacements
selection.Insert(text);

To summarize, how do I get a TextSelection instance from a ProjectItem instance?

Was it helpful?

Solution

As usual when dealing with the VS SDK, the answer is a bit obscure. The way that I solved it (right or wrong) is to make the ProjectItem instance the active document and then use the DTE2.ActiveDocument.Selection property to get the text. This is accomplished via the following:

if (!projectItem.IsOpen)
    projectItem.Open(@"{7651A701-06E5-11D1-8EBD-00A0C90F26EA}").Document.Activate(); //EnvDTE.Constants.vsViewKindCode

TextSelection selection = _vsApp.ActiveDocument.Selection;
selection.SelectAll();
string text = selection.Text;
selection.Delete();
//Do replacements
text = ReplaceTemplateValues(text, replacements);
selection.Insert(text);

Is there a better way?

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