示例#1
0
        public static int RegisterComObject(object obj, string monikerName)
        {
            IBindCtx            context = null;
            IRunningObjectTable rot     = null;
            IMoniker            moniker = null;

            CreateBindCtx(0, out context);
            context.GetRunningObjectTable(out rot);

            try
            {
                const int ROTFLAGS_REGISTRATIONKEEPSALIVE = 1;

                context.GetRunningObjectTable(out rot);

                const int S_OK = 0;

                if (CreateItemMoniker("", monikerName, out moniker) != S_OK)
                {
                    throw new Exception("Failed to create moniker");
                }

                var id = rot.Register(ROTFLAGS_REGISTRATIONKEEPSALIVE, obj, moniker);

                if (id == 0)
                {
                    throw new Exception("Failed to register object in ROT");
                }

                return(id);
            }
            finally
            {
                if (moniker != null)
                {
                    while (Marshal.ReleaseComObject(moniker) > 0)
                    {
                        ;
                    }
                }
                if (rot != null)
                {
                    while (Marshal.ReleaseComObject(rot) > 0)
                    {
                        ;
                    }
                }
                if (context != null)
                {
                    while (Marshal.ReleaseComObject(context) > 0)
                    {
                        ;
                    }
                }
            }
        }
        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);
        }
示例#3
0
        public static void UnregisterComObject(int id)
        {
            IBindCtx            context = null;
            IRunningObjectTable rot     = null;

            CreateBindCtx(0, out context);
            context.GetRunningObjectTable(out rot);

            try
            {
                rot.Revoke(id);
            }
            finally
            {
                if (rot != null)
                {
                    while (Marshal.ReleaseComObject(rot) > 0)
                    {
                        ;
                    }
                }

                if (context != null)
                {
                    while (Marshal.ReleaseComObject(context) > 0)
                    {
                        ;
                    }
                }
            }
        }
示例#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);
                }
            }
        }
        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);
        }
示例#6
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);
        }
示例#7
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);
            }
        }
    }
示例#8
0
        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);
        }
示例#9
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);
        }
示例#10
0
        /// <summary>
        /// [拡張]引数に指定された名前のワークブックを開いているアプリケーションを設定します。
        /// </summary>
        /// <exception cref="ArgumentNullException"></exception>
        /// <param name="WorkbookName">ワークブック名です。</param>
        static public Excel.Application setApps(this Excel.Application application, string WorkbookName)
        {
            //Excel.Application application = new Excel.Application();
            Boolean isSuccessed = false;

            if (WorkbookName == null || WorkbookName == "")
            {
                throw new ArgumentNullException();
            }

            // IBindCtx
            IBindCtx pBindCtx = null;

            CreateBindCtx(0, out pBindCtx);

            // IRunningObjectTable
            IRunningObjectTable pROT = null;

            pBindCtx.GetRunningObjectTable(out pROT);

            // IEnumMoniker
            IEnumMoniker pEnumMoniker = null;

            pROT.EnumRunning(out pEnumMoniker);

            pEnumMoniker.Reset();

            for (; ;)
            {
                // IMoniker
                IMoniker[] pMonikers = { null };

                IntPtr fetched = IntPtr.Zero;
                if (pEnumMoniker.Next(1, pMonikers, fetched) != 0)
                {
                    break;
                }

                // For Debug
                string strDisplayName;
                pMonikers[0].GetDisplayName(pBindCtx, null, out strDisplayName);
                Debug.WriteLine(strDisplayName);


                object         obj   = null;
                Excel.Workbook pBook = null;
                try
                {
                    pMonikers[0].BindToObject(pBindCtx, null, ref IID_IUnknown, out obj);

                    pBook = obj as Excel.Workbook;
                    if (pBook != null && pBook.Name == WorkbookName)
                    {
                        application = (Excel.Application)pBook.Application;
                        isSuccessed = true;
                        break;
                    }
                }
                catch (Exception)
                {
                }
                finally
                {
                    Marshal.ReleaseComObject(pMonikers[0]);
                }
            }

            Marshal.ReleaseComObject(pEnumMoniker);
            Marshal.ReleaseComObject(pROT);
            Marshal.ReleaseComObject(pBindCtx);

            if (!isSuccessed)
            {
                throw new NullReferenceException("起動中のExcelインスタンスが見つかりませんでした。");
            }
            return(application);
        }
示例#11
0
        // Regex for matching the VS DTE moniker as stored in the COM running object table.
        // Note the process id suffix to the string which we extract as capture group 1.
        // Example target: "!VisualStudio.DTE.11.0:11944"

        /// <summary>
        /// Returns collection of any/all EnvDTE.DTE instances running on the machine.
        /// http://blogs.msdn.com/b/kirillosenkov/archive/2011/08/10/how-to-get-dte-from-visual-studio-process-id.aspx
        /// </summary>
        /// <returns>Collection of EnvDTE.DTE instances keyed by the ID of the process running the DTE.</returns>
        public static Dictionary <int, EnvDTE.DTE> GetAllDTEs()
        {
            Dictionary <int, EnvDTE.DTE> dtes = new Dictionary <int, EnvDTE.DTE>();

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

                    // Parse the moniker to match against target spec. and extract process id.
                    int   processId;
                    Match match = s_regex_dteMoniker.Match(name);
                    if (!match.Success ||
                        match.Groups.Count != 2)
                    {
                        continue;
                    }
                    processId = int.Parse(match.Groups[1].Value);

                    // Store the DTE.
                    object runningObject = null;
                    Marshal.ThrowExceptionForHR(rot.GetObject(runningObjectMoniker, out runningObject));
                    dtes[processId] = (EnvDTE.DTE)runningObject;
                }
            }
            finally
            {
                if (enumMonikers != null)
                {
                    Marshal.ReleaseComObject(enumMonikers);
                }

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

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

            return(dtes);
        }
示例#12
0
        public static DTE GetCurrent()
        {
            var testRunnerProcess = Process.GetCurrentProcess();

            if (!TestRunners.Contains(testRunnerProcess.ProcessName.ToLower()))
            {
                throw new Exception("Test Runner Process not expected: " + testRunnerProcess.ProcessName.ToLower());
            }

            object runningObject = null;

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

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

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

                    string parentProcessName = null;

                    try
                    {
                        if (runningObjectMoniker != null)
                        {
                            runningObjectMoniker.GetDisplayName(bindCtx, null, out parentProcessName);
                        }
                    }
                    catch (UnauthorizedAccessException)
                    {
                        // do nothing.
                    }

                    var isVSProcess = IsVisualStudioProcessName(parentProcessName,
                                                                GetVisualStudioProcessId(testRunnerProcess.Id));

                    if (!isVSProcess)
                    {
                        continue;
                    }

                    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);
        }
示例#13
0
        /// <summary>
        /// [拡張]起動しているExcelの一覧を取得します。見つからない場合はnullを返します。
        /// TODO:返り値を2次元配列にして、PID返す。http://stackoverflow.com/questions/8490564/getting-excel-application-process-id
        /// </summary>
        /// <returns>ブック名の文字列配列です。</returns>
        static public string[] ListApps(this Excel.Application application)
        {
            List <String> arr = new List <String>();

            // IBindCtx
            IBindCtx pBindCtx = null;

            CreateBindCtx(0, out pBindCtx);

            // IRunningObjectTable
            IRunningObjectTable pROT = null;

            pBindCtx.GetRunningObjectTable(out pROT);

            // IEnumMoniker
            IEnumMoniker pEnumMoniker = null;

            pROT.EnumRunning(out pEnumMoniker);

            pEnumMoniker.Reset();

            for (; ;)
            {
                // IMoniker
                IMoniker[] pMonikers = { null };

                IntPtr fetched = IntPtr.Zero;
                if (pEnumMoniker.Next(1, pMonikers, fetched) != 0)
                {
                    break;
                }

                // For Debug
                string strDisplayName;
                pMonikers[0].GetDisplayName(pBindCtx, null, out strDisplayName);
                Debug.WriteLine(strDisplayName);


                object         obj   = null;
                Excel.Workbook pBook = null;
                try
                {
                    pMonikers[0].BindToObject(pBindCtx, null, ref IID_IUnknown, out obj);

                    pBook = obj as Excel.Workbook;
                    if (pBook != null)
                    {
                        arr.Add(pBook.Name);

                        //For Debug
                        //MessageBox.Show(pBook.Name);
                    }
                }
                catch (Exception)
                {
                }
                finally
                {
                    Marshal.ReleaseComObject(pMonikers[0]);
                }
            }

            Marshal.ReleaseComObject(pEnumMoniker);
            Marshal.ReleaseComObject(pROT);
            Marshal.ReleaseComObject(pBindCtx);

            if (arr.Count <= 0)
            {
                throw new NullReferenceException("開かれているワークブックが見つかりませんでした。");
            }
            return(arr.ToArray());
        }
示例#14
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);
        }
示例#15
0
        private T FindObjectByMonikerName <T>(string monikerName)
            where T : class
        {
            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((T)app);
                    }
                }
            }
            finally
            {
                if (monikers != null)
                {
                    Marshal.ReleaseComObject(monikers);
                }

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

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

            return(null);
        }
示例#16
0
        /// <summary>
        /// Get a COM handle to DTE of a running VS instance
        /// </summary>
        /// <param name="vsVersion">Version of Visual Studio (15.0 for 2017)</param>
        /// <param name="processId">Process ID of the running version</param>
        /// <returns></returns>
        public static DTE GetDTE(string vsVersion, int processId)
        {
            //var vsRunningInstance = BoundInstances.FirstOrDefault(x => x.ProcessId == processId && x.Version == vsVersion);
            //if (vsRunningInstance != null)
            //{
            //    return vsRunningInstance.VsInstance;
            //}

            string progId        = $"!VisualStudio.DTE.{vsVersion}:{processId.ToString()}";
            object runningObject = null;

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

            try
            {
                Marshal.ThrowExceptionForHR(WinApiProxy.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
                    {
                        runningObjectMoniker?.GetDisplayName(bindCtx, null, out name);
                        Debug.WriteLine($"Name = {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);
        }
示例#17
0
        static DTE FindRunningVSProWithOurProcess(int processId)
        {
            string              progId        = ":" + processId.ToString();
            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];
                    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.Contains(progId))
                    {
                        Marshal.ThrowExceptionForHR(rot.GetObject(runningObjectMoniker, out runningObject));
                        dte = runningObject as DTE;
                        if (dte != null)
                        {
                            break;
                        }
                    }
                }
            }
            finally
            {
                if (enumMonikers != null)
                {
                    Marshal.ReleaseComObject(enumMonikers);
                }

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

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

            return(dte);
        }
        private static void InitializeSolidWorks()
        {
            string              monikerName = "SolidWorks_PID_";
            object              app;
            IBindCtx            context  = null;
            IRunningObjectTable rot      = null;
            IEnumMoniker        monikers = null;

            try
            {
                CreateBindCtx(0, out context);

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

                IMoniker[] 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 ex)
                        {
                            MessageObserver.Instance.SetMessage("Failed to get SolidWorks_PID." + "\t" + ex, MessageType.Error);
                            System.Windows.Forms.MessageBox.Show(ex.Message);
                        }
                    }
                    if (name.Contains(monikerName))
                    {
                        rot.GetObject(curMoniker, out app);
                        swApp         = (SldWorks)app;
                        swApp.Visible = true;
                        swApp.DocumentVisible(false, 2);
                        swApp.DocumentVisible(false, 1);
                        return;
                    }
                }
                string progId = "SldWorks.Application";

                Type progType = Type.GetTypeFromProgID(progId);
                app           = Activator.CreateInstance(progType) as SldWorks;
                swApp         = (SldWorks)app;
                swApp.Visible = true;
                //swApp.DocumentVisible(false, 2);
                //swApp.DocumentVisible(false, 1);
                return;
            }
            finally
            {
                if (monikers != null)
                {
                    Marshal.ReleaseComObject(monikers);
                }
                if (rot != null)
                {
                    Marshal.ReleaseComObject(rot);
                }
                if (context != null)
                {
                    Marshal.ReleaseComObject(context);
                }
            }
        }
示例#19
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);
        }
示例#20
0
        public static TComObj TryGetComObjectByMonikerName <TComObj>(string monikerName, IXLogger logger = null)
        {
            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 ex)
                        {
                            logger?.Log(ex);
                        }
                    }

                    if (string.Equals(monikerName,
                                      name, StringComparison.CurrentCultureIgnoreCase))
                    {
                        object app;
                        rot.GetObject(curMoniker, out app);
                        return((TComObj)app);
                    }
                }
            }
            catch (Exception ex)
            {
                logger?.Log(ex);
                throw;
            }
            finally
            {
                if (monikers != null)
                {
                    while (Marshal.ReleaseComObject(monikers) > 0)
                    {
                        ;
                    }
                }

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

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

            return(default);
        /// <summary>
        /// Get the DTE which is associated to the new visual studio instance we created using Monkiker with ROT
        /// </summary>
        public DTE2 GetDTE()
        {
            LoadVisualStudio();

            string rotEntry      = String.Format("!{0}:{1}", DteVersion, 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);

                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, rotEntry, 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((DTE2)runningObject);
        }
示例#22
0
        /// <summary>
        /// Gets the DTE object from any devenv process.
        /// </summary>
        /// <returns>
        /// Retrieved DTE object or
        /// <see langword="null">
        /// if not found.
        /// </see>
        /// </returns>
        private static DTE GetDte()
        {
            object runningObject = null;

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

            try
            {
                Process process = Process.GetProcessesByName("devenv").SingleOrDefault();

                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
                    {
                        runningObjectMoniker?.GetDisplayName(bindCtx, null, out name);
                    }
                    catch (UnauthorizedAccessException)
                    {
                        // Do nothing, there is something in the ROT that we do not have access to.
                    }

                    Regex monikerRegex = new Regex(@"!VisualStudio.DTE\.\d+\.\d+\:" + process.Id, 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 DTE);
        }
示例#23
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);
        }
        internal static DTE GetCurrent(IServiceProvider serviceProvider = null)
        {
            if (serviceProvider != null)
            {
                return((DTE)serviceProvider.GetService(typeof(DTE)));
            }
            var                 currentProcess = System.Diagnostics.Process.GetCurrentProcess();
            var                 vsProcessId    = GetVisualStudioProcessId(currentProcess.Id);
            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.
                    }
                    if (string.IsNullOrEmpty(name) || !DteRegex.IsMatch(name))
                    {
                        continue;
                    }
                    if (!name.EndsWith(vsProcessId.ToString()))
                    {
                        continue;
                    }
                    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);
        }
示例#25
0
        public DTE GetDTE()
        {
            int processId = 0;

            foreach (var process in System.Diagnostics.Process.GetProcesses())
            {
                if (process.ProcessName.ToLower() == "devenv")
                {
                    if (process.MainWindowTitle.StartsWith("Hydra"))
                    {
                        processId = process.Id;
                    }
                }
            }

            if (processId != 0)
            {
                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);
            }
            else
            {
                return(null);
            }
        }
示例#26
0
        private static DTE GetDTE(int processId)
        {
#if DEV15
            // VS 2017 doesn't install some assemblies to the GAC that are needed to work with the
            // debugger, and as the tests don't execute in the devenv.exe process, those assemblies
            // fail to load - so load them manually from PublicAssemblies.

            // Use the executable name, as this is only needed for the out of proc test execution
            // that may interact with the debugger (vstest.executionengine.x86.exe).
            if (!DTELoaded)
            {
                string currentProc = Process.GetCurrentProcess().MainModule.FileName;
                if (StringComparer.OrdinalIgnoreCase.Equals(
                        Path.GetFileName(currentProc), "vstest.executionengine.x86.exe"))
                {
                    string baseDir          = Path.GetDirectoryName(currentProc);
                    string publicAssemblies = Path.Combine(baseDir, "..\\..\\..\\PublicAssemblies");

                    Assembly.LoadFrom(Path.Combine(publicAssemblies, "Microsoft.VisualStudio.OLE.Interop.dll"));
                    Assembly.LoadFrom(Path.Combine(publicAssemblies, "envdte90.dll"));
                    Assembly.LoadFrom(Path.Combine(publicAssemblies, "envdte80.dll"));
                    Assembly.LoadFrom(Path.Combine(publicAssemblies, "envdte.dll"));
                }
                DTELoaded = true;
            }
#endif
            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);
        }
        private IEnumerable <EnvDTE.DTE> GetDTEInstances(int?processId = null)
        {
            var                 dteInstances   = new List <DTE>();
            IBindCtx            bindCtx        = null;
            IRunningObjectTable runningObjects = null;
            IEnumMoniker        monikers       = null;

            var foundByProcessId = false;

            try
            {
                Marshal.ThrowExceptionForHR(WindowsAPI.CreateBindCtx(0, out bindCtx));

                bindCtx.GetRunningObjectTable(out runningObjects);

                runningObjects.EnumRunning(out monikers);

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

                while (monikers.Next(1, moniker, fetchedMonikers) == 0)
                {
                    moniker[0].GetDisplayName(bindCtx, null, out var rotName);

                    if (rotName.StartsWith("!VisualStudio.DTE.16.0:") || rotName.StartsWith("!VisualStudio.DTE.15.0:"))
                    {
                        Marshal.ThrowExceptionForHR(runningObjects.GetObject(moniker[0], out var runningObject));

                        if (runningObject is EnvDTE.DTE dte)
                        {
                            Logger.Instance.LogMessage(TracingLevel.INFO, $"ROT Object Found {rotName}");

                            if (processId.HasValue && int.TryParse(rotName.Substring(23), out var rotProcessId) && rotProcessId == processId)
                            {
                                foundByProcessId = true;

                                dteInstances.Clear();
                                dteInstances.Add(dte);

                                break;
                            }

                            dteInstances.Add(dte);
                        }
                    }
                }

                if (processId.HasValue && !foundByProcessId)
                {
                    return(Enumerable.Empty <EnvDTE.DTE>());
                }

                return(dteInstances.AsEnumerable());
            }
            finally
            {
                if (monikers != null)
                {
                    Marshal.ReleaseComObject(monikers);
                }

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

                if (bindCtx != null)
                {
                    Marshal.ReleaseComObject(bindCtx);
                }
            }
        }
示例#28
0
        public static Hashtable GetROT()
        {
            lock (lockthis)
            {
                Hashtable       objectList;
                List <IMoniker> rotList;
                rotList    = new List <IMoniker>();
                objectList = new Hashtable();
                IBindCtx            ctx   = null;
                IRunningObjectTable table = null;
                IEnumMoniker        mon   = null;
                IMoniker[]          lst   = new IMoniker[1];
                try
                {
                    NativeMethods.CreateBindCtx(0, out ctx);
                    ctx.GetRunningObjectTable(out table);
                    table.EnumRunning(out mon);
                    Debug.WriteLine("ROT:");
                    Debug.Indent();
                    while (mon.Next(1, lst, IntPtr.Zero) == 0)
                    {
                        string displayName;
                        lst[0].GetDisplayName(ctx, lst[0], out displayName);
                        //Debug.WriteLine(displayName);
                        if ((displayName.IndexOf("!C/SIDE!") != -1) /*&& (displayName.IndexOf("database=") !=-1)*/)
                        {
                            try
                            {
                                rotList.Add(lst[0]);
                                object   obj;
                                int      ret      = table.GetObject(lst[0], out obj);
                                ClientID clientID = new ClientID(obj);

                                int hash;
                                lst[0].Hash(out hash);
                                using (NAVClient c = new NAVClient(obj)) {
                                    //CheckInterface(obj);
                                    Debug.WriteLine(c.Hwnd + ":" + displayName);
                                    objectList[clientID.Id] = obj;
                                }
                            }
                            catch (Exception e)
                            {
                                Debug.WriteLine("ROT NAV Obj exception:" + e.Message);
                            }
                        }
                    }
                    Debug.Unindent();
                    return(objectList);
                }
                finally
                {
                    if (ctx != null)
                    {
                        Marshal.ReleaseComObject(ctx);
                    }
                    if (mon != null)
                    {
                        Marshal.ReleaseComObject(mon);
                    }
                    if (table != null)
                    {
                        Marshal.ReleaseComObject(table);
                    }
                }
            }
        }
示例#29
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);
    }
示例#30
0
        /// <summary>
        /// Visual Studioデバッガーにアタッチします。
        /// </summary>
        /// <param name="debuggerInfo">現在のプロセスをアタッチするデバッガー情報。</param>
        /// <returns><paramref name="debuggerInfo" />がVisual Studioのデバッガー情報で、アタッチに成功した場合は<c>True</c>。その他の場合は<c>False</c>。</returns>
        public override bool AttachToType(DebuggerInfo debuggerInfo)
        {
            if (debuggerInfo == null ||
                debuggerInfo.DebuggerType != typeof(VisualStudioDebuggerInfoProvider) ||
                !(debuggerInfo.ProcessId > 0))
            {
                return(false);
            }

            IBindCtx            bc          = null;
            IRunningObjectTable rot         = null;
            IEnumMoniker        enumMoniker = null;

            try
            {
                var r = NativeMethods.CreateBindCtx(0, out bc);
                Marshal.ThrowExceptionForHR(r);
                if (bc == null)
                {
                    throw new Win32Exception();
                }
                bc.GetRunningObjectTable(out rot);
                if (rot == null)
                {
                    throw new Win32Exception();
                }

                rot.EnumRunning(out enumMoniker);
                if (enumMoniker == null)
                {
                    throw new Win32Exception();
                }

                var cp        = Process.GetCurrentProcess().Id;
                var dteSuffix = ":" + debuggerInfo.ProcessId;

                var moniker = new IMoniker[1];
                while (enumMoniker.Next(1, moniker, IntPtr.Zero) == 0 && moniker[0] != null)
                {
                    string dn;

                    moniker[0].GetDisplayName(bc, null, out dn);

                    if (dn.StartsWith("!VisualStudio.DTE.") && dn.EndsWith(dteSuffix))
                    {
                        object dte, dbg, lps;
                        rot.GetObject(moniker[0], out dte);

                        for (var i = 0; i < 10; i++)
                        {
                            try
                            {
                                dbg = dte.GetType().InvokeMember("Debugger", BindingFlags.GetProperty, null, dte, null);
                                lps = dbg.GetType().InvokeMember("LocalProcesses", BindingFlags.GetProperty, null, dbg, null);
                                var lpn = (System.Collections.IEnumerator)lps.GetType().InvokeMember("GetEnumerator", BindingFlags.InvokeMethod, null, lps, null);

                                while (lpn.MoveNext())
                                {
                                    var pn = Convert.ToInt32(lpn.Current.GetType().InvokeMember("ProcessID", BindingFlags.GetProperty, null, lpn.Current, null));

                                    if (pn == cp)
                                    {
                                        lpn.Current.GetType().InvokeMember("Attach", BindingFlags.InvokeMethod, null, lpn.Current, null);
                                        return(true);
                                    }
                                }
                            }
                            catch (COMException)
                            {
                                Thread.Sleep(250);
                            }
                        }
                        Marshal.ReleaseComObject(moniker[0]);

                        break;
                    }

                    Marshal.ReleaseComObject(moniker[0]);
                }
                return(false);
            }
            finally
            {
                if (enumMoniker != null)
                {
                    Marshal.ReleaseComObject(enumMoniker);
                }
                if (rot != null)
                {
                    Marshal.ReleaseComObject(rot);
                }
                if (bc != null)
                {
                    Marshal.ReleaseComObject(bc);
                }
            }
        }