How to get DTE from Visual Studio process ID?

DTE is an automation framework that is used to programmatically control Visual Studio, often from another process. It internally uses COM remoting to execute commands from another process on the VS UI thread.

A while back I have written about How to start Visual Studio programmatically and get the DTE object to control the devenv.exe process. But how to get the DTE object to automate an already running Visual Studio instance? Or how to get the DTE object to automate Visual Studio started from an experimental hive (using the /rootsuffix command line option)?

Here’s the code (need to reference EnvDTE, which is a PIA, no pun intended):

When Visual Studio starts (regardless if it was passed the /rootsuffix command line argument), it places itself onto the Running Object Table (aka ROT). We know the moniker that the Visual Studio process will use to identify itself (it’s !VisualStudio.DTE.10.0:1234, where 1234 is the devenv.exe process ID). We then enumerate though all the objects in the ROT and find the one with the right moniker.

Then you can just keep using the DTE object as if you’re writing a macro (Visual Studio macros also use DTE to automate VS).