Capture method, class, assembly name from right click inside Visual Studio

1.5k views Asked by At

I'd like to write a Visual Studio Extension that captures the following information when a user right clicks a portion of code

  1. Detect if a user has clicked a method and if so get the method name

  2. Retrieve the full class name of the method ie (namespace + class name)

  3. Retrieve the containing project's output type ie, class library etc

  4. The full assembly name, ie path + name

I'm using a combination of EnvDTE object and IVsTextManager GetActiveView() method but I am unable to get all of the information I require. I've seen Test Driven do this when running unit tests inside Visual Studio via a right click so I am hoping I can achieve the same.

The only thing I've been able to extract is the method name to date but it requires the method name to be selected in the IDE. EnvDTE is good for returning the project name but that's not really any good to me.

var methodName = (EnvDTE.DTE)this.GetService(typeof(EnvDTE.DTE)).ActiveDocument.Object("").Selection.Text;

After this to get the class name/namespace all I have is a reference to the line that was selected, ie the method name. From here I read the selected file in the active window and read backwards from the method name to try and find the most recent occurrence of the class keyword and then namespace. It's very inelegant and clunky.

1

There are 1 answers

0
Sergey Vlasov On

You can get the method at the cursor with CodeElement:

DTE.ActiveWindow.Selection.ActivePoint.CodeElement(vsCMElement.vsCMElementFunction);

See also Discovering Code by Using the Code Model about the CodeModel class.