private static DTE GetDTE(int processId) { MessageFilter.Register(); var prefix = Process.GetProcessById(processId).ProcessName; if ("devenv".Equals(prefix, StringComparison.OrdinalIgnoreCase)) { prefix = "VisualStudio"; } string progId = string.Format("!{0}.DTE.{1}:{2}", prefix, AssemblyVersionInfo.VSVersion, processId); object runningObject = null; IBindCtx bindCtx = null; IRunningObjectTable rot = null; IEnumMoniker enumMonikers = null; try { Marshal.ThrowExceptionForHR(CreateBindCtx(reserved: 0, ppbc: out bindCtx)); bindCtx.GetRunningObjectTable(out rot); rot.EnumRunning(out enumMonikers); IMoniker[] moniker = new IMoniker[1]; uint numberFetched = 0; while (enumMonikers.Next(1, moniker, out numberFetched) == 0) { IMoniker runningObjectMoniker = moniker[0]; string name = null; try { if (runningObjectMoniker != null) { runningObjectMoniker.GetDisplayName(bindCtx, null, out name); } } catch (UnauthorizedAccessException) { // Do nothing, there is something in the ROT that we do not have access to. } if (!string.IsNullOrEmpty(name) && string.Equals(name, progId, StringComparison.Ordinal)) { rot.GetObject(runningObjectMoniker, out runningObject); break; } } } finally { if (enumMonikers != null) { Marshal.ReleaseComObject(enumMonikers); } if (rot != null) { Marshal.ReleaseComObject(rot); } if (bindCtx != null) { Marshal.ReleaseComObject(bindCtx); } } return((DTE)runningObject); }
// Start the filter. public static void Register() { IOleMessageFilter newFilter = new MessageFilter(); CoRegisterMessageFilter(newFilter, out IOleMessageFilter oldFilter); }