Beispiel #1
0
        public static IEnumerable <KeyValuePair <Process, EnvDTE._DTE> > GetVSInstances()
        {
            IRunningObjectTable runningObjectTable = WinApiHelper.GetRunningObjectTable();
            IEnumMoniker        enumMoniker;

            runningObjectTable.EnumRunning(out enumMoniker);
            IMoniker[] monikers = new IMoniker[1];
            for (enumMoniker.Reset(); enumMoniker.Next(1, monikers, IntPtr.Zero) == 0;)
            {
                EnvDTE._DTE dte;
                Process     dteProcess;
                try {
                    IBindCtx ctx = WinApiHelper.NewBindCtx();
                    string   runningObjectName;
                    monikers[0].GetDisplayName(ctx, null, out runningObjectName);
                    if (!runningObjectName.StartsWith("!VisualStudio") && !runningObjectName.StartsWith("!WDExpress.DTE"))
                    {
                        continue;
                    }
                    object runningObjectVal;
                    runningObjectTable.GetObject(monikers[0], out runningObjectVal);
                    dte = runningObjectVal as EnvDTE._DTE;
                    if (dte == null)
                    {
                        continue;
                    }
                    int dteProcessId = int.Parse(runningObjectName.Split(':')[1]);
                    dteProcess = Process.GetProcessById(dteProcessId);
                } catch {
                    continue;
                }
                yield return(new KeyValuePair <Process, EnvDTE._DTE>(dteProcess, dte));
            }
        }
        private EnvDTE.DTE GetDevToolsEnvironment(int 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);

                var moniker       = new IMoniker[1];
                var numberFetched = IntPtr.Zero;

                while (enumMonikers.Next(1, moniker, numberFetched) == 0)
                {
                    var runningObjectMoniker = moniker[0];

                    string name = null;

                    try
                    {
                        runningObjectMoniker?.GetDisplayName(bindCtx, null, out name);
                    }
                    catch (UnauthorizedAccessException)
                    {
                        // Do nothing, there is something in the ROT that we do not have access to
                    }

                    var monikerRegex = new Regex(@"!VisualStudio.DTE\.\d+\.\d+\:" + processId, RegexOptions.IgnoreCase);
                    if (!string.IsNullOrEmpty(name) && monikerRegex.IsMatch(name))
                    {
                        Marshal.ThrowExceptionForHR(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(runningObject as EnvDTE.DTE);
        }
        private static IEnumerable <IMoniker> GetRunningMonikers(this IRunningObjectTable rot)
        {
            IEnumMoniker monikersEnum;

            rot.EnumRunning(out monikersEnum);
            return(monikersEnum.ToEnumerable());
        }
Beispiel #4
0
        public static IEnumerable <object> GetRunningObjects(string namePattern = ".*")
        {
            IEnumMoniker        enumMoniker = null;
            IRunningObjectTable rot         = null;
            IBindCtx            bindCtx     = null;

            try
            {
                Marshal.ThrowExceptionForHR(Ole32.CreateBindCtx(0, out bindCtx));
                bindCtx.GetRunningObjectTable(out rot);
                rot.EnumRunning(out enumMoniker);

                var moniker = new IMoniker[1];
                var fetched = IntPtr.Zero;

                while (enumMoniker.Next(1, moniker, fetched) == S_OK)
                {
                    object runningObject = null;
                    try
                    {
                        var roMoniker = moniker.First();
                        if (roMoniker == null)
                        {
                            continue;
                        }
                        roMoniker.GetDisplayName(bindCtx, null, out var name);
                        if (!Regex.IsMatch(name, namePattern))
                        {
                            continue;
                        }
                        Marshal.ThrowExceptionForHR(rot.GetObject(roMoniker, out runningObject));
                    }
                    catch (UnauthorizedAccessException)
                    {
                        continue;
                    }

                    if (runningObject != null)
                    {
                        yield return(runningObject);
                    }
                }
            }
            finally
            {
                if (enumMoniker != null)
                {
                    Marshal.ReleaseComObject(enumMoniker);
                }
                if (rot != null)
                {
                    Marshal.ReleaseComObject(rot);
                }
                if (bindCtx != null)
                {
                    Marshal.ReleaseComObject(bindCtx);
                }
            }
        }
Beispiel #5
0
        /// <summary>
        /// Create a list of DSGrapheditROTEntry from IFilterGraphs on the ROT
        /// </summary>
        /// <returns></returns>
        public static List <DSGrapheditROTEntry> GetFilterGraphsFromROT()
        {
            IRunningObjectTable        rtt     = null;
            IEnumMoniker               enumMon = null;
            List <DSGrapheditROTEntry> rots    = new List <DSGrapheditROTEntry>();

            int hr = GetRunningObjectTable(0, out rtt);

            rtt.EnumRunning(out enumMon);
            enumMon.Reset();
            if (hr != 1)
            {
                try
                {
                    IMoniker[] mon = new IMoniker[1];
                    while ((enumMon.Next(1, mon, IntPtr.Zero) == 0))
                    {
                        try
                        {
                            IBindCtx pctx; string displayName;
                            CreateBindCtx(0, out pctx);
                            // Get the name of the file
                            mon[0].GetDisplayName(pctx, null, out displayName);
                            // Clean up
                            Marshal.ReleaseComObject(pctx);
                            if (displayName.StartsWith("!FilterGraph"))
                            {
                                DSGrapheditROTEntry ds1 = new DSGrapheditROTEntry(displayName, mon[0]);
                                if (ds1._processName == "MediaPortal")
                                {
                                    rots.Add(ds1);
                                }
                                else
                                {
                                    ds1.Dispose();
                                }
                            }
                            else
                            {
                                Marshal.ReleaseComObject(mon[0]);
                            }
                        }
                        catch
                        {
                            Marshal.ReleaseComObject(mon[0]);
                            //throw;
                        }
                    }
                }
                finally
                {
                    Marshal.ReleaseComObject(enumMon);
                }
            }

            return(rots);
        }
Beispiel #6
0
        internal static DTE GetInstance(string solution)
        {
            const string visualStudioProgId = "!VisualStudio.DTE.";

            IRunningObjectTable runningObjectTable = null;
            IEnumMoniker        enumMoniker        = null;
            IBindCtx            bindCtx            = null;

            try
            {
                Marshal.ThrowExceptionForHR(GetRunningObjectTable(0, out runningObjectTable));
                runningObjectTable.EnumRunning(out enumMoniker);

                IMoniker[] monikers = new IMoniker[1];
                enumMoniker.Reset();

                Marshal.ThrowExceptionForHR(CreateBindCtx(0, out bindCtx));

                while (enumMoniker.Next(1, monikers, IntPtr.Zero) == 0)
                {
                    string displayName;
                    monikers[0].GetDisplayName(bindCtx, null, out displayName);

                    if (displayName.StartsWith(visualStudioProgId))
                    {
                        object o;
                        Marshal.ThrowExceptionForHR(runningObjectTable.GetObject(monikers[0], out o));

                        var d = (DTE)o;

                        if (d.Solution.FullName.EndsWith(solution, StringComparison.InvariantCultureIgnoreCase))
                        {
                            return(d);
                        }
                    }
                }
            }
            finally
            {
                if (runningObjectTable != null)
                {
                    Marshal.ReleaseComObject(runningObjectTable);
                }

                if (enumMoniker != null)
                {
                    Marshal.ReleaseComObject(enumMoniker);
                }

                if (bindCtx != null)
                {
                    Marshal.ReleaseComObject(bindCtx);
                }
            }

            return(null);
        }
        private static DTE GetDTE(int processId, Version version)
        {
            MessageFilter.Register();

            var    process    = Process.GetProcessById(processId);
            string progIdName = "VisualStudio";

            switch (process.MainModule.ModuleName.ToLowerInvariant())
            {
            case "wdexpress.exe":
                progIdName = "WDExpress";
                break;

            case "vwdexpress.exe":
                progIdName = "VWDExpress";
                break;
            }

            string progId        = string.Format("!{0}.DTE.{1}:{2}", progIdName, version, processId);
            object runningObject = null;

            IBindCtx            bindCtx      = null;
            IRunningObjectTable rot          = null;
            IEnumMoniker        enumMonikers = null;

            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;
                }
            }

            return((DTE)runningObject);
        }
Beispiel #8
0
        public static DTE GetDte(int processId)
        {
            var    progId        = "!TcXaeShell.DTE.15.0:" + processId;
            object runningObject = null;

            IBindCtx            bindCtx      = null;
            IRunningObjectTable rot          = null;
            IEnumMoniker        enumMonikers = null;

            try
            {
                Marshal.ThrowExceptionForHR(CreateBindCtx(0, out bindCtx));
                bindCtx.GetRunningObjectTable(out rot);
                rot.EnumRunning(out enumMonikers);

                var moniker       = new IMoniker[1];
                var numberFetched = IntPtr.Zero;
                while (enumMonikers.Next(1, moniker, numberFetched) == 0)
                {
                    var    runningObjectMoniker = moniker[0];
                    string name = null;
                    try
                    {
                        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))
                    {
                        continue;
                    }
                    Marshal.ThrowExceptionForHR(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);
        }
Beispiel #9
0
        /// <summary>Locates the DTE object for the specified process.</summary>
        public static DTE TryLocateDteForProcess(Process process)
        {
            object dte = null;
            IRunningObjectTable runningObjectTable = null;
            IEnumMoniker        enumMoniker        = null;
            IBindCtx            bindContext        = null;
            var monikers = new IMoniker[1];
            var vsProgId = VisualStudioInstanceFactory.VsProgId;

            Ole32.GetRunningObjectTable(0, out runningObjectTable);
            runningObjectTable.EnumRunning(out enumMoniker);
            Ole32.CreateBindCtx(0, out bindContext);

            do
            {
                monikers[0] = null;

                var monikersFetched = 0u;
                var hresult         = enumMoniker.Next(1, monikers, out monikersFetched);

                if (hresult == VSConstants.S_FALSE)
                {
                    // There's nothing further to enumerate, so fail
                    return(null);
                }
                else
                {
                    Marshal.ThrowExceptionForHR(hresult);
                }

                var    moniker         = monikers[0];
                string fullDisplayName = null;

                moniker.GetDisplayName(bindContext, null, out fullDisplayName);

                var displayNameProcessId = 0;

                // FullDisplayName will look something like: <ProgID>:<ProccessId>
                if (!int.TryParse(fullDisplayName.Split(':').Last(), out displayNameProcessId))
                {
                    continue;
                }

                var displayName = fullDisplayName.Substring(0, (fullDisplayName.Length - (displayNameProcessId.ToString().Length + 1)));
                var fullProgId  = vsProgId.StartsWith("!") ? vsProgId : $"!{vsProgId}";

                if (displayName.Equals(fullProgId, StringComparison.OrdinalIgnoreCase) &&
                    (displayNameProcessId == process.Id))
                {
                    runningObjectTable.GetObject(moniker, out dte);
                }
            }while (dte == null);

            return((DTE)(dte));
        }
        public static object GetRunningCOMObjectByName(string objectDisplayName)
        {
            IRunningObjectTable runningObjectTable = null;
            IEnumMoniker        monikerList        = null;

            try
            {
                if (GetRunningObjectTable(0, out runningObjectTable) != 0 || runningObjectTable == null)
                {
                    return(null);
                }

                runningObjectTable.EnumRunning(out monikerList);
                monikerList.Reset();

                IMoniker[] monikerContainer       = new IMoniker[1];
                IntPtr     pointerFetchedMonikers = IntPtr.Zero;

                while (monikerList.Next(1, monikerContainer, pointerFetchedMonikers) == 0)
                {
                    IBindCtx bindInfo;
                    string   displayName;

                    CreateBindCtx(0, out bindInfo);
                    monikerContainer[0].GetDisplayName(bindInfo, null, out displayName);
                    Marshal.ReleaseComObject(bindInfo);

                    if (displayName.IndexOf(objectDisplayName, StringComparison.OrdinalIgnoreCase) != -1)
                    {
                        object comInstance;
                        runningObjectTable.GetObject(monikerContainer[0], out comInstance);
                        return(comInstance);
                    }
                }
            }
            catch
            {
                return(null);
            }
            finally
            {
                if (runningObjectTable != null)
                {
                    Marshal.ReleaseComObject(runningObjectTable);
                }

                if (monikerList != null)
                {
                    Marshal.ReleaseComObject(monikerList);
                }
            }
            return(null);
        }
Beispiel #11
0
        public excel.Workbook GetActiveWorkbook(string xlfile)
        {
            IRunningObjectTable prot      = null;
            IEnumMoniker        pmonkenum = null;

            try
            {
                IntPtr pfetched = IntPtr.Zero;
                // Query the running object table (ROT)
                if (GetRunningObjectTable(0, out prot) != 0 || prot == null)
                {
                    return(null);
                }
                prot.EnumRunning(out pmonkenum);
                pmonkenum.Reset();
                IMoniker[] monikers = new IMoniker[1];
                while (pmonkenum.Next(1, monikers, pfetched) == 0)
                {
                    IBindCtx pctx; string filepathname;
                    CreateBindCtx(0, out pctx);
                    // Get the name of the file
                    monikers[0].GetDisplayName(pctx, null, out filepathname);
                    // Clean up
                    Marshal.ReleaseComObject(pctx);
                    // Search for the workbook
                    if (filepathname.IndexOf(xlfile) != -1)
                    {
                        object roval;
                        // Get a handle on the workbook
                        prot.GetObject(monikers[0], out roval);
                        return(roval as excel.Workbook);
                    }
                }
            }
            catch
            {
                return(null);
            }
            finally
            {
                // Clean up
                if (prot != null)
                {
                    Marshal.ReleaseComObject(prot);
                }
                if (pmonkenum != null)
                {
                    Marshal.ReleaseComObject(pmonkenum);
                }
            }
            return(null);
        }
        static DTE FindRunningVSProWithOurSolution(string solutionPath)
        {
            DTE                 dte           = null;
            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];
                IntPtr     numberFetched = IntPtr.Zero;
                while (enumMonikers.Next(1, moniker, numberFetched) == 0)
                {
                    IMoniker runningObjectMoniker = moniker[0];
                    Marshal.ThrowExceptionForHR(rot.GetObject(runningObjectMoniker, out runningObject));
                    var dte2 = runningObject as DTE;
                    if (dte2 != null)
                    {
                        if (dte2.Solution.FullName == solutionPath)
                        {
                            dte = dte2;
                            break;
                        }
                    }
                }
            }
            finally
            {
                if (enumMonikers != null)
                {
                    Marshal.ReleaseComObject(enumMonikers);
                }

                if (rot != null)
                {
                    Marshal.ReleaseComObject(rot);
                }

                if (bindCtx != null)
                {
                    Marshal.ReleaseComObject(bindCtx);
                }
            }

            return(dte);
        }
Beispiel #13
0
        // Get the Excel workbook from the running object table
        private Excel.Workbook RetrieveWorkbook(string excelFile)
        {
            IRunningObjectTable pROT         = null;
            IEnumMoniker        pMonikerEnum = null;

            try
            {
                IntPtr pFetched = IntPtr.Zero;
                if (GetRunningObjectTable(0, out pROT) != 0 || pROT == null)
                {
                    return(null);
                }

                pROT.EnumRunning(out pMonikerEnum);
                pMonikerEnum.Reset();
                IMoniker[] monikers = new IMoniker[1];
                while (pMonikerEnum.Next(1, monikers, pFetched) == 0)
                {
                    IBindCtx pCTX;
                    string   filePathName;
                    CreateBindCtx(0, out pCTX);
                    monikers[0].GetDisplayName(pCTX, null, out filePathName);
                    Marshal.ReleaseComObject(pCTX);
                    if (filePathName.IndexOf(excelFile) != -1)
                    {
                        object roVal;
                        pROT.GetObject(monikers[0], out roVal);
                        if (roVal is Excel.Workbook)
                        {
                            return(roVal as Excel.Workbook);
                        }
                    }
                }
            }
            catch
            {
                return(null);
            }
            finally
            {
                if (pROT != null)
                {
                    Marshal.ReleaseComObject(pROT);
                }
                if (pMonikerEnum != null)
                {
                    Marshal.ReleaseComObject(pMonikerEnum);
                }
            }
            return(null);
        }
Beispiel #14
0
        public static object GetActiveObject(string progId)
        {
            // Convert the prog id into a class id
            string classId = ConvertProgIdToClassId(progId);

            IRunningObjectTable prot      = null;
            IEnumMoniker        pMonkEnum = null;

            try
            {
                IntPtr Fetched = IntPtr.Zero;
                // Open the running objects table.
                NativeMethods.GetRunningObjectTable(0, out prot);
                prot.EnumRunning(out pMonkEnum);
                pMonkEnum.Reset();
                IMoniker[] pmon = new IMoniker[1];

                // Iterate through the results
                while (pMonkEnum.Next(1, pmon, Fetched) == 0)
                {
                    IBindCtx pCtx;

                    NativeMethods.CreateBindCtx(0, out pCtx);

                    string displayName;
                    pmon[0].GetDisplayName(pCtx, null, out displayName);

                    Marshal.ReleaseComObject(pCtx);
                    if (displayName.IndexOf(classId) != -1)
                    {
                        // Return the matching object
                        object objReturnObject;
                        int    ret = prot.GetObject(pmon[0], out objReturnObject);
                        return(objReturnObject);
                    }
                }
                return(null);
            }
            finally
            {
                // Free resources
                if (prot != null)
                {
                    Marshal.ReleaseComObject(prot);
                }
                if (pMonkEnum != null)
                {
                    Marshal.ReleaseComObject(pMonkEnum);
                }
            }
        }
Beispiel #15
0
        private static object GetRunningObject(string displayName, out IEnumerable <string> runningObjectDisplayNames)
        {
            IBindCtx bindContext = null;

            NativeMethods.CreateBindCtx(0, out bindContext);

            IRunningObjectTable runningObjectTable = null;

            bindContext.GetRunningObjectTable(out runningObjectTable);

            IEnumMoniker monikerEnumerator = null;

            runningObjectTable.EnumRunning(out monikerEnumerator);

            object        runningObject = null;
            List <string> runningObjectDisplayNameList = new List <string>();

            IMoniker[] monikers      = new IMoniker[1];
            IntPtr     numberFetched = IntPtr.Zero;

            while (monikerEnumerator.Next(1, monikers, numberFetched) == 0)
            {
                IMoniker moniker = monikers[0];

                string objectDisplayName = null;
                try
                {
                    moniker.GetDisplayName(bindContext, null, out objectDisplayName);
                }
                catch (UnauthorizedAccessException)
                {
                    // Some ROT objects require elevated permissions.
                }

                if (!string.IsNullOrWhiteSpace(objectDisplayName))
                {
                    runningObjectDisplayNameList.Add(objectDisplayName);
                    if (objectDisplayName.EndsWith(displayName, StringComparison.Ordinal))
                    {
                        runningObjectTable.GetObject(moniker, out runningObject);
                        if (runningObject == null)
                        {
                            throw new InvalidOperationException($"Failed to get running object with display name {displayName}");
                        }
                    }
                }
            }

            runningObjectDisplayNames = runningObjectDisplayNameList;
            return(runningObject);
        }
Beispiel #16
0
    /// <summary>
    /// Returns an object from the ROT, given a prog Id.
    /// </summary>
    /// <param name="progId">The prog id of the object to return.</param>
    /// <returns>The requested object, or null if the object is not found.</returns>
    public static object GetActiveObject(string progId)
    {
        // Convert the prog id into a class id
        string classId = ConvertProgIdToClassId(progId);

        IRunningObjectTable runningObjectTable = null;
        IEnumMoniker        monikerEnumerator  = null;
        IBindCtx            ctx = null;

        try
        {
            IntPtr numFetched = new IntPtr();
            // Open the running objects table.
            CreateBindCtx(0, out ctx);
            ctx.GetRunningObjectTable(out runningObjectTable);
            runningObjectTable.EnumRunning(out monikerEnumerator);
            monikerEnumerator.Reset();
            IMoniker[] monikers = new IMoniker[1];

            // Iterate through the results
            while (monikerEnumerator.Next(1, monikers, numFetched) == 0)
            {
                string runningObjectName;
                monikers[0].GetDisplayName(ctx, null, out runningObjectName);
                if (runningObjectName.IndexOf(classId) != -1)
                {
                    // Return the matching object
                    object objReturnObject;
                    runningObjectTable.GetObject(monikers[0], out objReturnObject);
                    return(objReturnObject);
                }
            }
            return(null);
        }
        finally
        {
            // Free resources
            if (runningObjectTable != null)
            {
                Marshal.ReleaseComObject(runningObjectTable);
            }
            if (monikerEnumerator != null)
            {
                Marshal.ReleaseComObject(monikerEnumerator);
            }
            if (ctx != null)
            {
                Marshal.ReleaseComObject(ctx);
            }
        }
    }
Beispiel #17
0
        public static DTE2 GetDTE2(DTE dte)
        {
            try
            {
                List <DTE2> dte2List = new List <DTE2>();

                IRunningObjectTable runningObjectTable = null;
                NativeMethods.GetRunningObjectTable(0, out runningObjectTable);

                IEnumMoniker enumMoniker = null;
                runningObjectTable.EnumRunning(out enumMoniker);

                enumMoniker.Reset();
                IntPtr     fetched = IntPtr.Zero;
                IMoniker[] moniker = new IMoniker[1];

                while (enumMoniker.Next(1, moniker, fetched) == 0)
                {
                    IBindCtx bindCtx = null;
                    NativeMethods.CreateBindCtx(0, out bindCtx);

                    string displayName = "";
                    moniker[0].GetDisplayName(bindCtx, null, out displayName);
                    // add all VisualStudio ROT entries to list
                    if (displayName.StartsWith("!VisualStudio"))
                    {
                        object comObject;
                        runningObjectTable.GetObject(moniker[0], out comObject);
                        dte2List.Add((DTE2)comObject);
                    }
                }

                // find the correct dte2 instance (each running VS instance has one...)
                KeyValuePair <DTE2, int> maxMatch = new KeyValuePair <DTE2, int>(null, 0);
                foreach (DTE2 dte2 in dte2List)
                {
                    int m = StringUtility.GetMatchingCharsFromStart(dte.Solution.FullName, dte2.Solution.FullName);
                    if (m > maxMatch.Value)
                    {
                        maxMatch = new KeyValuePair <DTE2, int>(dte2, m);
                    }
                }

                return(maxMatch.Key);
            }
            catch (Exception e)
            {
                Logging.Logging.LogError("Exception: " + e.Message);
                return(null);
            }
        }
        public void VisitRunning(Action <IMoniker> visitor)
        {
            // TODO: null check
            IEnumMoniker enumMoniker;

            _rot.EnumRunning(out enumMoniker);

            IntPtr fetched = IntPtr.Zero;

            IMoniker[] moniker = new IMoniker[1];
            while (enumMoniker.Next(1, moniker, fetched) == 0)
            {
                visitor(moniker[0]);
            }
        }
Beispiel #19
0
        private static DTE2 SeekDTE2InstanceFromROT(String moniker)
        {
            //
            IRunningObjectTable prot      = null;
            IEnumMoniker        pmonkenum = null;
            IntPtr pfeteched = IntPtr.Zero;

            DTE2 ret = null;

            try
            {
                //get rot
                if ((GetRunningObjectTable(0, out prot) != 0) || (prot == null))
                {
                    return(ret);
                }
                prot.EnumRunning(out pmonkenum);
                pmonkenum.Reset();
                IMoniker[] monikers = new IMoniker[1];
                while (pmonkenum.Next(1, monikers, pfeteched) == 0)
                {
                    String   insname;
                    IBindCtx pctx;
                    CreateBindCtx(0, out pctx);
                    monikers[0].GetDisplayName(pctx, null, out insname);
                    Marshal.ReleaseComObject(pctx);
                    if (string.Compare(insname, moniker) == 0) //lookup by item moniker
                    {
                        Object obj;
                        prot.GetObject(monikers[0], out obj);
                        ret = (DTE2)obj;
                    }
                }
            }
            finally
            {
                if (prot != null)
                {
                    Marshal.ReleaseComObject(prot);
                }
                if (pmonkenum != null)
                {
                    Marshal.ReleaseComObject(pmonkenum);
                }
            }
            return(ret);
        }
        public static IList <string> GetRunningCOMObjectNames()
        {
            IList <string>      result             = new List <string>();
            IRunningObjectTable runningObjectTable = null;
            IEnumMoniker        monikerList        = null;

            try
            {
                if (GetRunningObjectTable(0, out runningObjectTable) != 0 || runningObjectTable == null)
                {
                    return(null);
                }
                runningObjectTable.EnumRunning(out monikerList);
                monikerList.Reset();
                IMoniker[] monikerContainer       = new IMoniker[1];
                IntPtr     pointerFetchedMonikers = IntPtr.Zero;
                while (monikerList.Next(1, monikerContainer, pointerFetchedMonikers) == 0)
                {
                    IBindCtx bindInfo;
                    string   displayName;
                    CreateBindCtx(0, out bindInfo);
                    monikerContainer[0].GetDisplayName(bindInfo, null, out displayName);
                    Marshal.ReleaseComObject(bindInfo);
                    result.Add(displayName);
                }
                return(result);
            }
            catch
            {
                return(null);
            }
            finally
            {
                if (runningObjectTable != null)
                {
                    Marshal.ReleaseComObject(runningObjectTable);
                }
                if (monikerList != null)
                {
                    Marshal.ReleaseComObject(monikerList);
                }
            }
        }
        private static List <(IMoniker moniker, IBindCtx bindingContext, object instance)> GetRunningComObjects()
        {
            List <(IMoniker, IBindCtx, object)> result = new List <(IMoniker, IBindCtx, object)>();
            IRunningObjectTable runningObjectTable     = null;
            IEnumMoniker        monikerList            = null;

            try
            {
                if (Program.GetRunningObjectTable(0, out runningObjectTable) != 0 ||
                    runningObjectTable == null)
                {
                    return(result);
                }

                runningObjectTable.EnumRunning(out monikerList);
                monikerList.Reset();
                IMoniker[] monikerContainer       = new IMoniker[1];
                IntPtr     pointerFetchedMonikers = IntPtr.Zero;
                while (monikerList.Next(1, monikerContainer, pointerFetchedMonikers) == 0)
                {
                    Program.CreateBindCtx(0, out IBindCtx bindingContext);
                    runningObjectTable.GetObject(monikerContainer[0], out object comInstance);
                    result.Add((monikerContainer[0], bindingContext, comInstance));
                }
            }
            finally
            {
                if (runningObjectTable != null)
                {
                    Marshal.ReleaseComObject(runningObjectTable);
                }

                if (monikerList != null)
                {
                    Marshal.ReleaseComObject(monikerList);
                }
            }

            return(result);
        }
Beispiel #22
0
    public static DTE GetDTE(int processId)
    {
        string progId        = "!VisualStudio.DTE.10.0:" + processId.ToString();
        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];
            IntPtr     numberFetched = IntPtr.Zero;
            while (enumMonikers.Next(1, moniker, 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))
                {
                    Marshal.ThrowExceptionForHR(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);
    }
        // Requires Using System.Runtime.InteropServices.ComTypes

        // Get all running instance by querying ROT

        private List <object> GetRunningInstances(string[] progIds)

        {
            List <string> clsIds = new List <string>();



            // get the app clsid

            foreach (string progId in progIds)

            {
                Type type = Type.GetTypeFromProgID(progId);



                if (type != null)
                {
                    clsIds.Add(type.GUID.ToString().ToUpper());
                }
            }



            // get Running Object Table ...

            IRunningObjectTable Rot = null;

            GetRunningObjectTable(0, out Rot);

            if (Rot == null)
            {
                return(null);
            }



            // get enumerator for ROT entries

            IEnumMoniker monikerEnumerator = null;

            Rot.EnumRunning(out monikerEnumerator);



            if (monikerEnumerator == null)
            {
                return(null);
            }



            monikerEnumerator.Reset();



            List <object> instances = new List <object>();



            IntPtr pNumFetched = new IntPtr();

            IMoniker[] monikers = new IMoniker[1];



            // go through all entries and identifies app instances

            while (monikerEnumerator.Next(1, monikers, pNumFetched) == 0)

            {
                IBindCtx bindCtx;

                CreateBindCtx(0, out bindCtx);

                if (bindCtx == null)
                {
                    continue;
                }



                string displayName;

                monikers[0].GetDisplayName(bindCtx, null, out displayName);



                foreach (string clsId in clsIds)

                {
                    if (displayName.ToUpper().IndexOf(clsId) > 0)

                    {
                        object ComObject;

                        Rot.GetObject(monikers[0], out ComObject);



                        if (ComObject == null)
                        {
                            continue;
                        }



                        instances.Add(ComObject);

                        break;
                    }
                }
            }



            return(instances);
        }
Beispiel #24
0
        private static ISldWorks GetSwAppFromProcess(int processId)
        {
            var monikerName = "SolidWorks_PID_" + processId.ToString();

            IBindCtx            context  = null;
            IRunningObjectTable rot      = null;
            IEnumMoniker        monikers = null;

            try
            {
                CreateBindCtx(0, out context);

                context.GetRunningObjectTable(out rot);
                rot.EnumRunning(out monikers);

                var moniker = new IMoniker[1];

                while (monikers.Next(1, moniker, IntPtr.Zero) == 0)
                {
                    var curMoniker = moniker.First();

                    string name = null;

                    if (curMoniker != null)
                    {
                        try
                        {
                            curMoniker.GetDisplayName(context, null, out name);
                        }
                        catch (UnauthorizedAccessException)
                        {
                        }
                    }

                    if (string.Equals(monikerName,
                                      name, StringComparison.CurrentCultureIgnoreCase))
                    {
                        object app;
                        rot.GetObject(curMoniker, out app);
                        return(app as ISldWorks);
                    }
                }
            }
            finally
            {
                if (monikers != null)
                {
                    Marshal.ReleaseComObject(monikers);
                }

                if (rot != null)
                {
                    Marshal.ReleaseComObject(rot);
                }

                if (context != null)
                {
                    Marshal.ReleaseComObject(context);
                }
            }

            return(null);
        }
Beispiel #25
0
        //FAILS////////////////////////////////////////////////////////////////////////////

        //
        //fetch workbook
        public excel.Workbook RetrieveWorkbook(string xlfile)
        {
            Console.WriteLine("START Retrieve Workbook");
            IRunningObjectTable prot      = null;
            IEnumMoniker        pmonkenum = null;

            try
            {
                IntPtr pfetched = IntPtr.Zero;
                // Query the running object table (ROT)
                if (GetRunningObjectTable(0, out prot) != 0 || prot == null)
                {
                    Console.WriteLine("Retrieved object NULL");
                    return(null);
                }
                prot.EnumRunning(out pmonkenum); pmonkenum.Reset();
                IMoniker[] monikers = new IMoniker[1];
                while (pmonkenum.Next(1, monikers, pfetched) == 0)
                {
                    IBindCtx pctx;
                    string   filepathname;
                    CreateBindCtx(0, out pctx);
                    // Get the name of the file
                    monikers[0].GetDisplayName(pctx, null, out filepathname);
                    // Clean up
                    Marshal.ReleaseComObject(pctx);
                    // Search for the workbook
                    if (filepathname.IndexOf(xlfile) != -1)
                    {
                        object roval;
                        // Get a handle on the workbook
                        prot.GetObject(monikers[0], out roval);
                        //good return type
                        return(roval as excel.Workbook);
                    }
                }
            }
            catch
            {
                MessageBox.Show("Excel retrieve workbook failed");
                return(null);
            }
            finally
            {
                //if (m_Workbook == null) {
                //	Console.WriteLine("failed to retrieve workbook");
                //}
                // Clean up
                if (prot != null)
                {
                    Marshal.ReleaseComObject(prot);
                }
                if (pmonkenum != null)
                {
                    Marshal.ReleaseComObject(pmonkenum);
                }
            }

            Console.WriteLine("END Retrieve Workbook");
            return(null);
        }
Beispiel #26
0
        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);
        }
        /// <summary>
        /// Returns all running com proxies + add. information from the running object table there matched with the input parameters
        /// WARNING: the method returns always the first com proxy from the running object table if multiple (match) proxies exists.
        /// </summary>
        /// <returns>IDisposableEnumeration with proxy information</returns>
        public static IDisposableSequence <ProxyInformation> GetActiveProxyInformations()
        {
            IEnumMoniker        monikerList             = null;
            IRunningObjectTable runningObjectTable      = null;
            RunningObjectTableItemCollection resultList = new RunningObjectTableItemCollection();

            try
            {
                // query table and returns null if no objects running
                if (GetRunningObjectTable(0, out runningObjectTable) != 0 || runningObjectTable == null)
                {
                    return(null);
                }

                // query moniker & reset
                runningObjectTable.EnumRunning(out monikerList);
                monikerList.Reset();

                IMoniker[] monikerContainer       = new IMoniker[1];
                IntPtr     pointerFetchedMonikers = IntPtr.Zero;

                // fetch all moniker
                while (monikerList.Next(1, monikerContainer, pointerFetchedMonikers) == 0)
                {
                    // query com proxy info
                    object comInstance = null;
                    runningObjectTable.GetObject(monikerContainer[0], out comInstance);
                    if (null == comInstance)
                    {
                        continue;
                    }

                    string name      = TypeDescriptor.GetClassName(comInstance);
                    string component = TypeDescriptor.GetComponentName(comInstance, false);

                    IBindCtx bindInfo    = null;
                    string   displayName = String.Empty;
                    Guid     classID     = Guid.Empty;
                    if (CreateBindCtx(0, out bindInfo) == 0)
                    {
                        monikerContainer[0].GetDisplayName(bindInfo, null, out displayName);
                        monikerContainer[0].GetClassID(out classID);
                        TryMarshalReleaseComObject(bindInfo);
                    }

                    string itemClassName     = TypeDescriptor.GetClassName(comInstance);
                    string itemComponentName = TypeDescriptor.GetComponentName(comInstance);

                    COMTypes.ITypeInfo typeInfo    = null;
                    string             itemLibrary = String.Empty;
                    if (classID != Guid.Empty)
                    {
                        typeInfo    = TryCreateTypeInfo(comInstance);
                        itemLibrary = null != typeInfo?GetParentLibraryGuid(typeInfo).ToString() : String.Empty;
                    }

                    string itemID = classID != Guid.Empty ? classID.ToString() : String.Empty;

                    ProxyInformation entry =
                        new ProxyInformation(comInstance, displayName, itemID, itemClassName,
                                             itemComponentName, itemLibrary, IntPtr.Zero, ProxyInformation.ProcessElevation.Unknown);

                    resultList.Add(entry);
                    if (classID != Guid.Empty && typeInfo != null)
                    {
                        ReleaseTypeInfo(typeInfo);
                    }
                }

                return(resultList);
            }
            catch (Exception exception)
            {
                DebugConsole.Default.WriteException(exception);
                throw;
            }
            finally
            {
                // release proxies
                if (runningObjectTable != null)
                {
                    TryMarshalReleaseComObject(runningObjectTable);
                }
                if (monikerList != null)
                {
                    TryMarshalReleaseComObject(monikerList);
                }
            }
        }
        /// <summary>
        /// Returns all running com proxies from the running object table there matched with the input parameters
        /// WARNING: the method returns always the first com proxy from the running object table if multiple (match) proxies exists.
        /// </summary>
        /// <param name="componentName">component name, for example Excel, null is a wildcard </param>
        /// <param name="className">class name, for example Application, null is a wildcard </param>
        /// <returns>COM proxy enumerator</returns>
        public static IDisposableSequence GetActiveProxies(string componentName, string className)
        {
            IEnumMoniker        monikerList        = null;
            IRunningObjectTable runningObjectTable = null;
            List <object>       resultList         = new List <object>();

            try
            {
                // query table and returns null if no objects running
                if (GetRunningObjectTable(0, out runningObjectTable) != 0 || runningObjectTable == null)
                {
                    return(null);
                }

                // query moniker & reset
                runningObjectTable.EnumRunning(out monikerList);
                monikerList.Reset();

                IMoniker[] monikerContainer       = new IMoniker[1];
                IntPtr     pointerFetchedMonikers = IntPtr.Zero;

                // fetch all moniker
                while (monikerList.Next(1, monikerContainer, pointerFetchedMonikers) == 0)
                {
                    // query com proxy info
                    object comInstance = null;
                    runningObjectTable.GetObject(monikerContainer[0], out comInstance);
                    if (null == comInstance)
                    {
                        continue;
                    }

                    // get class name and component name
                    string name      = TypeDescriptor.GetClassName(comInstance);
                    string component = TypeDescriptor.GetComponentName(comInstance, false);

                    // match for equal and add to list
                    bool componentNameEqual = String.IsNullOrWhiteSpace(component) ? true :
                                              (componentName.Equals(component, StringComparison.InvariantCultureIgnoreCase));
                    bool classNameEqual = String.IsNullOrWhiteSpace(className) ? true :
                                          (className.Equals(name, StringComparison.InvariantCultureIgnoreCase));

                    if (componentNameEqual && classNameEqual)
                    {
                        resultList.Add(comInstance);
                    }
                    else
                    {
                        componentNameEqual = ((_ballmersPlace + componentName).Equals(component, StringComparison.InvariantCultureIgnoreCase));
                        if (componentNameEqual && classNameEqual)
                        {
                            resultList.Add(comInstance);
                        }
                        else
                        {
                            if (comInstance.GetType().IsCOMObject)
                            {
                                TryMarshalReleaseComObject(comInstance);
                            }
                        }
                    }
                }

                return(new DisposableObjectList(resultList.ToArray()));
            }
            catch (Exception exception)
            {
                DebugConsole.Default.WriteException(exception);
                throw;
            }
            finally
            {
                // release proxies
                if (runningObjectTable != null)
                {
                    TryMarshalReleaseComObject(runningObjectTable);
                }
                if (monikerList != null)
                {
                    TryMarshalReleaseComObject(monikerList);
                }
            }
        }
        /// <summary>
        /// Returns a running com proxy from the running object table. the method takes the first proxy there matched with the input parameters.
        /// WARNING: the method returns always the first com proxy from the running object table if multiple (match) proxies exists.
        /// </summary>
        /// <param name="componentName">component name, for example Excel</param>
        /// <param name="className">class name, for example Application</param>
        /// <param name="throwExceptionIfNothingFound">throw an exception if no proxy was found</param>
        /// <returns>a native COM proxy</returns>
        public static object GetActiveProxy(string componentName, string className, bool throwExceptionIfNothingFound)
        {
            if (String.IsNullOrEmpty(componentName))
            {
                throw new ArgumentNullException("componentName");
            }
            if (String.IsNullOrEmpty(className))
            {
                throw new ArgumentNullException("className");
            }

            IEnumMoniker        monikerList        = null;
            IRunningObjectTable runningObjectTable = null;

            try
            {
                // query table and returns null if no objects runnings
                if (GetRunningObjectTable(0, out runningObjectTable) != 0 || runningObjectTable == null)
                {
                    return(null);
                }

                // query moniker & reset
                runningObjectTable.EnumRunning(out monikerList);
                monikerList.Reset();

                IMoniker[] monikerContainer       = new IMoniker[1];
                IntPtr     pointerFetchedMonikers = IntPtr.Zero;

                // fetch all moniker
                while (monikerList.Next(1, monikerContainer, pointerFetchedMonikers) == 0)
                {
                    // query com proxy info
                    object comInstance = null;
                    runningObjectTable.GetObject(monikerContainer[0], out comInstance);
                    if (null == comInstance)
                    {
                        continue;
                    }

                    // get class name and component name
                    string name      = TypeDescriptor.GetClassName(comInstance);
                    string component = TypeDescriptor.GetComponentName(comInstance, false);

                    // match for equal and return
                    bool componentNameEqual = (componentName.Equals(component, StringComparison.InvariantCultureIgnoreCase));
                    bool classNameEqual     = (className.Equals(name, StringComparison.InvariantCultureIgnoreCase));

                    if (componentNameEqual && classNameEqual)
                    {
                        return(comInstance);
                    }
                    else
                    {
                        componentNameEqual = ((_ballmersPlace + componentName).Equals(component, StringComparison.InvariantCultureIgnoreCase));
                        if (componentNameEqual && classNameEqual)
                        {
                            return(comInstance);
                        }
                        else
                        {
                            if (comInstance.GetType().IsCOMObject)
                            {
                                TryMarshalReleaseComObject(comInstance);
                            }
                        }
                    }
                }

                if (throwExceptionIfNothingFound)
                {
                    throw new COMException("Target instance is not running.");
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception exception)
            {
                DebugConsole.Default.WriteException(exception);
                throw;
            }
            finally
            {
                // release proxies
                if (runningObjectTable != null)
                {
                    TryMarshalReleaseComObject(runningObjectTable);
                }
                if (monikerList != null)
                {
                    TryMarshalReleaseComObject(monikerList);
                }
            }
        }
Beispiel #30
0
        private static DTE FindDTE(string file)
        {
            const string id = "!VisualStudio.DTE.";

            IBindCtx            bindCtx      = null;
            IRunningObjectTable rot          = null;
            IEnumMoniker        enumMonikers = null;

            try
            {
                Marshal.ThrowExceptionForHR(CreateBindCtx(0, out bindCtx));
                bindCtx.GetRunningObjectTable(out rot);
                rot.EnumRunning(out enumMonikers);

                IMoniker[] moniker       = new IMoniker[1];
                IntPtr     numberFetched = IntPtr.Zero;
                while (enumMonikers.Next(1, moniker, 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) && name.StartsWith(id, StringComparison.Ordinal))
                    {
                        object runningObject;
                        Marshal.ThrowExceptionForHR(rot.GetObject(runningObjectMoniker, out runningObject));
                        var dte = runningObject as DTE;
                        if (dte != null && dte.Solution.FindProjectItem(file) != null)
                        {
                            Console.WriteLine(dte.Solution.FindProjectItem(file).Name);
                            return(dte);
                        }
                    }
                }
            }
            finally
            {
                if (enumMonikers != null)
                {
                    Marshal.ReleaseComObject(enumMonikers);
                }
                if (rot != null)
                {
                    Marshal.ReleaseComObject(rot);
                }
                if (bindCtx != null)
                {
                    Marshal.ReleaseComObject(bindCtx);
                }
            }

            return(null);
        }