14

Im writing a visual studio (2010) extension with a right click menu whilst in a code view. I want to be able to examine the current code from my menu item event handler but havent been able to find somewhere in the object model to do this.

How do i access the code in the current window in a visual studio extension?

EDIT

Heres the code i used to get the current document text

 DTE dte = Package.GetGlobalService(typeof(DTE)) as DTE ;
 TextDocument activeDoc = dte.ActiveDocument.Object() as TextDocument;

 var text = activeDoc.CreateEditPoint(activeDoc.StartPoint).GetText(activeDoc.EndPoint);
undefined
  • 33,537
  • 22
  • 129
  • 198
  • 1
    Are you starting from a MEF component? If so do you have an ITextView or do you want to grab the active one? – JaredPar Jan 28 '12 at 02:53
  • 1
    @JaredPar I think its MPF, i couldn't work out how to use MEF to connect to VS, i just started from the VSPackage template. – undefined Jan 28 '12 at 04:54
  • @JaredPar Is there an easy 2020 way to get the active view when starting with MEF? – Pavel Sapehin Nov 15 '20 at 04:03
  • Update: It seems like it's possible to implement `IWpfTextViewConnectionListener` and export it as another interface with `IWpfTextView ActiveDocument { get; }` property. This property can be set in `SubjectBuffersConnected` and unset in `SubjectBuffersDisconnected`. – Pavel Sapehin Nov 16 '20 at 05:29
  • I've created another question and posted a possible solution in the Update 1: [How to get active IWpfTextView in VS2019 extension (MEF)](https://stackoverflow.com/questions/65453407/how-to-get-active-iwpftextview-in-vs2019-extension-mef) – Pavel Sapehin Dec 26 '20 at 05:23

1 Answers1

12

You may be looking for

Document doc = DTE.ActiveDocument;
TextDocument txt = doc.Object() as TextDocument;

You should then be able to edit work with the TextDocument as needed.

Mark Smith
  • 1,085
  • 8
  • 19
  • 2
    Ok ive gotten the TextDocument, but i cant work out how to get the current code from the document – undefined Jan 28 '12 at 06:42
  • 2
    There's not much room in comments so I'll just point you to what on MSDN you should be looking at. Look up StartPoint on the Document object, It's a TextPoint which has methods to access CodeElement's. And if you look at [CodeElement on MSDN](http://msdn.microsoft.com/en-us/library/envdte.textpoint.codeelement.aspx). This example might be useful. – Mark Smith Jan 28 '12 at 14:25