Esempio n. 1
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];
                while (enumMonikers.Next(1, moniker, IntPtr.Zero) == 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);
        }
        public static DTE GetDTE(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);

                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) && Regex.Match(name, "VisualStudio.*" + processId).Success)
                    {
                        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);
        }
Esempio n. 3
0
        public static object GetInstanceFromROT(RunningObjectTableComponentInfo RunningComponent)
        {
            IEnumMoniker monikerList = null;
            IRunningObjectTable runningObjectTable = null;
            object ResultInstance = 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)
                {
                    // create binding object
                    IBindCtx bindInfo;
                    CreateBindCtx(0, out bindInfo);

                    // query com proxy info      
                    object comInstance = null;
                    runningObjectTable.GetObject(monikerContainer[0], out comInstance);

                    string ppszDisplayName;
                    try { monikerContainer[0].GetDisplayName(bindInfo, null, out ppszDisplayName); }
                    catch { ppszDisplayName = ""; }

                    Guid pClassID;
                    try { monikerContainer[0].GetClassID(out pClassID); }
                    catch { pClassID = Guid.Empty; }

                    string ClassName;
                    try { ClassName = TypeDescriptor.GetClassName(comInstance); }
                    catch { ClassName = ""; }

                    string ComponentName;
                    try { ComponentName = TypeDescriptor.GetComponentName(comInstance, false); }
                    catch { ComponentName = ""; }

                    if ((RunningComponent.DisplayName == ppszDisplayName) &&
                        (RunningComponent.ClsID == pClassID) &&
                        (RunningComponent.ComponentClassName == ClassName) &&
                        (RunningComponent.ComponentName == ComponentName)
                        )
                    {
                        Marshal.ReleaseComObject(bindInfo);
                        ResultInstance = comInstance;
                    }
                    else
                        Marshal.ReleaseComObject(comInstance);

                    Marshal.ReleaseComObject(bindInfo);
                }
                
                return ResultInstance;
            }
            finally
            {
                // release proxies
                if (runningObjectTable != null)
                    Marshal.ReleaseComObject(runningObjectTable);
                if (monikerList != null)
                    Marshal.ReleaseComObject(monikerList);
            }
        }
Esempio n. 4
0
        /// <summary> Populate the InnerList with a list of filters from a particular category </summary>
        protected void getFilters(Guid category)
        {
            int            hr;
            object         comObj  = null;
            ICreateDevEnum enumDev = null;

#if DSHOWNET
            IEnumMoniker enumMon = null;
            IMoniker[]   mon     = new IMoniker[1];
#else
#if VS2003
            UCOMIEnumMoniker enumMon = null;
            UCOMIMoniker[]   mon     = new UCOMIMoniker[1];
#else
            IEnumMoniker enumMon = null;
            IMoniker[]   mon     = new IMoniker[1];
#endif
#endif

            try
            {
#if DSHOWNET
                // Get the system device enumerator
                Type srvType = Type.GetTypeFromCLSID(Clsid.SystemDeviceEnum);
                if (srvType == null)
                {
                    throw new NotImplementedException("System Device Enumerator");
                }
                comObj  = Activator.CreateInstance(srvType);
                enumDev = (ICreateDevEnum)comObj;

                // Create an enumerator to find filters in category
                hr = enumDev.CreateClassEnumerator(ref category, out enumMon, 0);
#else
                enumDev = (ICreateDevEnum) new CreateDevEnum();

                // Create an enumerator to find filters in category
                hr = enumDev.CreateClassEnumerator(category, out enumMon, 0);
#endif
                if (hr != 0)
//#if NEWCODE
                {
                    if (category == FilterCategory.VideoInputDevice)
                    {
                        MessageBox.Show("Warning No Video Input Devices");
                        return;
                        //throw new NotSupportedException( "No devices of the category VideoInputDevice" );
                    }
                    else if (category == FilterCategory.AudioInputDevice)
                    {
//						throw new NotSupportedException( "No devices of the category AudioInputDevice" );
                        return;
                    }
                    else if (category == FilterCategory.VideoCompressorCategory)
                    {
                        MessageBox.Show("Warning No Video Input Devices");
                        return;
                        //throw new NotSupportedException("No devices of the category VideoCompressorCategory");
                    }
                    else
                    if (category == FilterCategory.AudioCompressorCategory)
                    {
                        throw new NotSupportedException("No devices of the category AudioCompressorCategory");
                    }
                    else
                    {
                        throw new NotSupportedException("No devices of the category " + category.ToString());
                    }
                }
//#else
//				throw new NotSupportedException( "No devices of the category" );
//#endif

                // Loop through the enumerator
#if DSHOWNET
                IntPtr f = IntPtr.Zero;
#else
#if VS2003
                int f = 0;
#else
                IntPtr f = IntPtr.Zero;
#endif
#endif
                do
                {
                    // Next filter
#if DSHOWNET
                    hr = enumMon.Next(1, mon, f);
#else
#if VS2003
                    hr = enumMon.Next(1, mon, out f);
#else
                    hr = enumMon.Next(1, mon, f);
#endif
#endif
                    if ((hr != 0) || (mon[0] == null))
                    {
                        break;
                    }

                    // Add the filter
                    Filter filter = new Filter(mon[0]);
                    InnerList.Add(filter);

                    // Release resources
                    Marshal.ReleaseComObject(mon[0]);
                    mon[0] = null;
                }while(true);

                // Sort
                InnerList.Sort();
            }
            finally
            {
                enumDev = null;
                if (mon[0] != null)
                {
                    Marshal.ReleaseComObject(mon[0]);
                }
                mon[0] = null;
                if (enumMon != null)
                {
                    Marshal.ReleaseComObject(enumMon);
                }
                enumMon = null;
                if (comObj != null)
                {
                    Marshal.ReleaseComObject(comObj);
                }
                comObj = null;
            }
        }
        /// <summary> Populate the InnerList with a list of filters from a particular category </summary>
        protected void getFilters(Guid category)
        {
            int            hr;
            object         comObj  = null;
            ICreateDevEnum enumDev = null;
            IEnumMoniker   enumMon = null;

            IMoniker[] mon = new IMoniker[1];

            try
            {
                // Get the system device enumerator
                Type srvType = Type.GetTypeFromCLSID(Clsid.SystemDeviceEnum);
                if (srvType == null)
                {
                    throw new NotImplementedException("System Device Enumerator");
                }
                comObj  = Activator.CreateInstance(srvType);
                enumDev = (ICreateDevEnum)comObj;

                // Create an enumerator to find filters in category
                hr = enumDev.CreateClassEnumerator(category, out enumMon, 0);
                //if( hr != 0 )
                //    throw new NotSupportedException( "No devices of the category" );
                if (hr == 0)
                {
                    // Loop through the enumerator
                    IntPtr f = IntPtr.Zero;
                    do
                    {
                        // Next filter
                        hr = enumMon.Next(1, mon, f);
                        if ((hr != 0) || (mon[0] == null))
                        {
                            break;
                        }

                        // Add the filter
                        Filter filter = new Filter(mon[0]);
                        InnerList.Add(filter);

                        // Release resources
                        Marshal.ReleaseComObject(mon[0]);
                        mon[0] = null;
                    }while (true);
                }
                // Sort
                InnerList.Sort();
            }
            finally
            {
                enumDev = null;
                if (mon[0] != null)
                {
                    Marshal.ReleaseComObject(mon[0]);
                }
                mon[0] = null;
                if (enumMon != null)
                {
                    Marshal.ReleaseComObject(enumMon);
                }
                enumMon = null;
                if (comObj != null)
                {
                    Marshal.ReleaseComObject(comObj);
                }
                comObj = null;
            }
        }
Esempio n. 6
0
        public static bool GetDevicesOfCat(Guid cat, out ArrayList devs)
        {
            devs = null;
            object         comObj  = null;
            ICreateDevEnum enumDev = null;
            IEnumMoniker   enumMon = null;
            var            mon     = new IMoniker[1];

            try
            {
                var srvType = Type.GetTypeFromCLSID(Uuid.Clsid.SystemDeviceEnum);
                if (srvType == null)
                {
                    throw new NotImplementedException("System Device Enumerator");
                }

                comObj  = Activator.CreateInstance(srvType);
                enumDev = (ICreateDevEnum)comObj;
                var hr = enumDev.CreateClassEnumerator(ref cat, out enumMon, 0);
                if (hr != 0)
                {
                    throw new NotSupportedException("No devices of the category");
                }

                int    count = 0;
                IntPtr f     = IntPtr.Zero;
                do
                {
                    hr = enumMon.Next(1, mon, f);
                    if ((hr != 0) || (mon[0] == null))
                    {
                        break;
                    }
                    var dev = new DsDevice();
                    dev.Name = GetFriendlyName(mon[0]);
                    if (devs == null)
                    {
                        devs = new ArrayList();
                    }
                    dev.Mon            = mon[0]; mon[0] = null;
                    devs.Add(dev); dev = null;
                    count++;
                }while (true);

                return(count > 0);
            }
            catch (Exception)
            {
                if (devs != null)
                {
                    foreach (DsDevice d in devs)
                    {
                        d.Dispose();
                    }
                    devs = null;
                }
                return(false);
            }
            finally
            {
                enumDev = null;
                if (mon[0] != null)
                {
                    Marshal.ReleaseComObject(mon[0]);
                }
                mon[0] = null;
                if (enumMon != null)
                {
                    Marshal.ReleaseComObject(enumMon);
                }
                enumMon = null;
                if (comObj != null)
                {
                    Marshal.ReleaseComObject(comObj);
                }
                comObj = null;
            }
        }
        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)
                        {
                            MessageBox.Show("Failed to get SolidWorks_PID." + "\t" + ex);
                        }
                    }
                    if (name.Contains(monikerName))
                    {
                        rot.GetObject(curMoniker, out app);
                        swApp         = (SldWorks)app;
                        swApp.Visible = true;
                        return;
                    }
                }
                string progId = "SldWorks.Application";

                Type progType = Type.GetTypeFromProgID(progId);
                app           = Activator.CreateInstance(progType) as SldWorks;
                swApp         = (SldWorks)app;
                swApp.Visible = true;
                return;
            }
            finally
            {
                if (monikers != null)
                {
                    Marshal.ReleaseComObject(monikers);
                }
                if (rot != null)
                {
                    Marshal.ReleaseComObject(rot);
                }
                if (context != null)
                {
                    Marshal.ReleaseComObject(context);
                }
            }
        }
Esempio n. 8
0
        public static TComObj TryGetComObjectByMonikerName <TComObj>(string monikerName)
        {
            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((TComObj)app);
                    }
                }
            }
            finally
            {
                if (monikers != null)
                {
                    Marshal.ReleaseComObject(monikers);
                }

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

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

            return(default(TComObj));
        }
Esempio n. 9
0
        public static DsDevice[] GetH264Devices()
        {
            DsDevice[] devret;
            ArrayList  devs = new ArrayList();

            IFilterMapper2 pMapper = (IFilterMapper2) new FilterMapper2();

            Guid[] arrayInTypes = new Guid[2]
            {
                MediaType.Video,
                //new Guid(0x8d2d71cb, 0x243f, 0x45e3, 0xb2, 0xd8, 0x5f, 0xd7, 0x96, 0x7e, 0xc0, 0x9b)
                new Guid(0x34363248, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71)                         // FOURCC H264
            };
            IEnumMoniker pEnum = null;
            int          hr    = pMapper.EnumMatchingFilters(out pEnum,
                                                             0,                                // Reserved.
                                                             true,                             // Use exact match?
                                                             (Merit)((int)Merit.DoNotUse + 1), // Minimum merit.
                                                             true,                             // At least one input pin?
                                                             1,                                // Number of major type/subtype pairs for input.
                                                             arrayInTypes,                     // Array of major type/subtype pairs for input.
                                                             null,                             // Input medium.
                                                             null,                             // Input pin category.
                                                             false,                            // Must be a renderer?
                                                             true,                             // At least one output pin?
                                                             0,                                // Number of major type/subtype pairs for output.
                                                             null,                             // Array of major type/subtype pairs for output.
                                                             null,                             // Output medium.
                                                             null);                            // Output pin category.

            DsError.ThrowExceptionForHR(hr);

            if (hr >= 0 && pEnum != null)
            {
                try
                {
                    try
                    {
                        // Enumerate the monikers.
                        IMoniker[] pMoniker = new IMoniker[1];
                        while (pEnum.Next(1, pMoniker, IntPtr.Zero) == 0)
                        {
                            try
                            {
                                // The devs array now owns this object.  Don't
                                // release it if we are going to be successfully
                                // returning the devret array
                                devs.Add(new DsDevice(pMoniker[0]));
                            }
                            catch
                            {
                                Marshal.ReleaseComObject(pMoniker[0]);
                                throw;
                            }
                        }
                    }
                    finally
                    {
                        // Clean up.
                        Marshal.ReleaseComObject(pEnum);
                    }


                    // Copy the ArrayList to the DsDevice[]
                    devret = new DsDevice[devs.Count];
                    devs.CopyTo(devret);
                }
                catch
                {
                    foreach (DsDevice d in devs)
                    {
                        d.Dispose();
                    }
                    throw;
                }
            }
            else
            {
                devret = new DsDevice[0];
            }

            Marshal.ReleaseComObject(pMapper);

            return(devret);
        }
Esempio n. 10
0
        public static AudioEncoder FindByFriendlyName(string friendlyName)
        {
            if (string.IsNullOrEmpty(friendlyName))
            {
                throw new ArgumentNullException("friendlyName");
            }

            ICreateDevEnum deviceEnumerator = null;

            try
            {
                deviceEnumerator = (ICreateDevEnum) new CreateDevEnum();

                IEnumMoniker monikerEnum = null;

                try
                {
                    int hr =
                        deviceEnumerator.CreateClassEnumerator(FilterGraphTools.CLSID_AudioCompressorCategory,
                                                               out monikerEnum, CDef.None);
                    DsError.ThrowExceptionForHR(hr);

                    IMoniker[] monikers = new IMoniker[1];

                    while (true)
                    {
                        try
                        {
                            hr = monikerEnum.Next(1, monikers, IntPtr.Zero);

                            DsError.ThrowExceptionForHR(hr);


                            Guid id = FilterGraphTools.IID_IPropertyBag;

                            if (monikers[0] == null)
                            {
                                break;
                            }

                            string discoveredFriendlyName;
                            object bag = null;

                            try
                            {
                                monikers[0].BindToStorage(null, null, ref id, out bag);

                                IPropertyBag propertyBag = (IPropertyBag)bag;

                                object variantName;
                                hr = propertyBag.Read("FriendlyName", out variantName, null);
                                DsError.ThrowExceptionForHR(hr);

                                discoveredFriendlyName = Convert.ToString(variantName);
                            }
                            finally
                            {
                                if (bag != null)
                                {
                                    Marshal.ReleaseComObject(bag);
                                }
                            }

                            if (friendlyName.ToLowerInvariant() != discoveredFriendlyName.ToLowerInvariant())
                            {
                                continue;
                            }

                            Guid id2 = FilterGraphTools.IID_IBaseFilter;

                            object filter;

                            monikers[0].BindToObject(null, null, ref id2, out filter);

                            if (filter != null)
                            {
                                return(new AudioEncoder(friendlyName, (IBaseFilter)filter));
                            }
                        }
                        finally
                        {
                            if (monikers[0] != null)
                            {
                                Marshal.ReleaseComObject(monikers[0]);
                            }
                        }
                    }
                }
                finally
                {
                    if (monikerEnum != null)
                    {
                        Marshal.ReleaseComObject(monikerEnum);
                    }
                }
            }
            finally
            {
                if (deviceEnumerator != null)
                {
                    Marshal.ReleaseComObject(deviceEnumerator);
                }
            }

            return(null);
        }
        /// <summary>
        /// 从 ROT 中获取 SolidWorks 程序
        /// </summary>
        /// <param name="processId">进程 id</param>
        /// <returns>SldWorks</returns>
        private SldWorks GetSolidWorksFromProcess(int processId)
        {
            // 进程名字
            string monikerName = "SolidWorks_PID_" + processId.ToString();

            // 绑定上下文
            IBindCtx context = null;

            // 运行时对象表 Running Object Table
            IRunningObjectTable rot = null;

            // 运行时对象名称集合
            IEnumMoniker monikers = null;

            try
            {
                // 创建绑定上下文
                CreateBindCtx(0, out context);

                // 获取运行时对象表 Running Object Table
                context.GetRunningObjectTable(out rot);

                // 列出运行时对象名称
                rot.EnumRunning(out monikers);

                //
                IMoniker[] moniker = new IMoniker[1];

                while (monikers.Next(1, moniker, IntPtr.Zero) == 0)
                {
                    // 当前名字
                    IMoniker 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))
                    {
                        // 从ROT获取对象并返回
                        rot.GetObject(curMoniker, out object app);

                        SldWorks sldWorks = app as SldWorks;

                        // 这一句不起作用
                        sldWorks.Visible = false;

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

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

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

            return(null);
        }
        /// <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="throwOnError">throw an exception if no proxy was found</param>
        /// <returns>a native COM proxy</returns>
        public static object GetActiveProxyFromROT(string componentName, string className, bool throwOnError)
        {
            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);

                    // 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)
                            {
                                Marshal.ReleaseComObject(comInstance);
                            }
                        }
                    }
                }

                if (throwOnError)
                {
                    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)
                {
                    Marshal.ReleaseComObject(runningObjectTable);
                }
                if (monikerList != null)
                {
                    Marshal.ReleaseComObject(monikerList);
                }
            }
        }
 void System.ServiceModel.ComIntegration.IMoniker.Enum(bool fForward, out IEnumMoniker ppenumMoniker)
 {
     throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotImplementedException());
 }
 public void Enum(bool fForward, out IEnumMoniker ppenumMoniker)
 {
     throw new NotImplementedException();
 }
        /// <summary>
        /// Füllt eine Liste mit Filterinformationen aus einer Auflistung.
        /// </summary>
        /// <param name="category">Die Art des Filters.</param>
        /// <param name="uniqueProp">Die Eigenschaft, die als eindeutige Kennung verwendet werden soll.</param>
        /// <param name="list">Die Informationen.</param>
        /// <param name="monikers">Die Auflistung.</param>
        public void LoadFromEnumeration( Guid category, string uniqueProp, List<FilterInformation> list, IEnumMoniker monikers )
        {
            // Nothing to do
            if (monikers == null)
                return;

            // With cleanup
            try
            {
                // Process all
                for (; ; )
                    using (var array = new COMArray( 1 ))
                    {
                        // Load
                        uint count;
                        if (monikers.Next( 1, array.Address, out count ) != 0)
                            break;

                        // Load object
                        if (count != 1)
                            continue;

                        // Load the one
                        var moniker = array.GetObject<IMoniker>( 0 );
                        try
                        {
                            // Remember
                            list.Add( new FilterInformation( category, moniker.ReadProperty( "FriendlyName" ), moniker.ReadProperty( uniqueProp ), m_MediaDevices ) );
                        }
                        finally
                        {
                            // Cleanup
                            BDAEnvironment.Release( ref moniker );
                        }
                    }
            }
            finally
            {
                // Cleanup
                BDAEnvironment.Release( ref monikers );
            }
        }
Esempio n. 16
0
        // Test this
        // http://adndevblog.typepad.com/autocad/2013/12/accessing-com-applications-from-the-running-object-table.html
        public static object GetRunningInstance(string progId)
        {
            // get the app clsid
            string clsId = string.Empty;
            Type   type  = Type.GetTypeFromProgID(progId);

            if (type != null)
            {
                clsId = 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();

            object instance = null;

            IntPtr pNumFetched = new IntPtr();

            IMoniker[] monikers = new IMoniker[1];

            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);
                if (displayName.ToUpper().IndexOf(clsId) > 0)
                {
                    object ComObject;
                    Rot.GetObject(monikers[0], out ComObject);

                    if (ComObject == null)
                    {
                        continue;
                    }

                    instance = ComObject;
                    break;
                }
            }

            return(instance);
        }
Esempio n. 17
0
        /// <summary>モニカを列挙する。</summary>
        /// <remarks>モニカとはCOMオブジェクトを識別する別名のこと。</remarks>
        private static void EnumMonikers(Guid category, Func <IMoniker, IPropertyBag, bool> func)
        {
            IEnumMoniker   enumerator = null;
            ICreateDevEnum device     = null;

            try
            {
                // ICreateDevEnum インターフェース取得.
                device = (ICreateDevEnum)Activator.CreateInstance(
                    Type.GetTypeFromCLSID(DsGuid.CLSID_SystemDeviceEnum));

                // IEnumMonikerの作成.
                device.CreateClassEnumerator(ref category, ref enumerator, 0);

                // 列挙可能なデバイスが存在しない場合null
                if (enumerator == null)
                {
                    return;
                }

                // 列挙.
                var monikers = new IMoniker[1];
                var fetched  = IntPtr.Zero;

                while (enumerator.Next(monikers.Length, monikers, fetched) == 0)
                {
                    var moniker = monikers[0];

                    // プロパティバッグへのバインド.
                    object value = null;
                    Guid   guid  = DsGuid.IID_IPropertyBag;
                    moniker.BindToStorage(null, null, ref guid, out value);
                    var prop = (IPropertyBag)value;

                    try
                    {
                        // trueで列挙完了。falseで継続する。
                        var rc = func(moniker, prop);
                        if (rc == true)
                        {
                            break;
                        }
                    }
                    finally
                    {
                        // プロパティバッグの解放
                        Marshal.ReleaseComObject(prop);

                        // 列挙したモニカの解放.
                        if (moniker != null)
                        {
                            Marshal.ReleaseComObject(moniker);
                        }
                    }
                }
            }
            finally
            {
                if (enumerator != null)
                {
                    Marshal.ReleaseComObject(enumerator);
                }
                if (device != null)
                {
                    Marshal.ReleaseComObject(device);
                }
            }
        }
Esempio n. 18
0
        public static IBaseFilter GetDeviceFilterByName(string deviceName, Guid filterCategory)
        {         //https://docs.microsoft.com/en-us/windows/win32/directshow/selecting-a-capture-device
            int hResult = 0;

            IBaseFilter  foundFilter = null;
            IEnumMoniker classEnum   = null;

            try
            {
                ICreateDevEnum devEnum = null;
                try
                {
                    devEnum = (ICreateDevEnum) new CreateDevEnum();
                    hResult = devEnum.CreateClassEnumerator(filterCategory, out classEnum, 0);

                    DsError.ThrowExceptionForHR(hResult);
                }
                finally
                {
                    if (devEnum != null)
                    {
                        Marshal.ReleaseComObject(devEnum);
                    }
                }

                if (classEnum != null)
                {
                    IMoniker[] monikerItems = new IMoniker[1];
                    while (classEnum.Next(monikerItems.Length, monikerItems, IntPtr.Zero) == 0)
                    {
                        var moniker = monikerItems[0];
                        try
                        {
                            Guid iid = typeof(IPropertyBag).GUID;

                            moniker.BindToStorage(null, null, ref iid, out var props);

                            IPropertyBag property = (props as IPropertyBag);
                            if (property != null)
                            {
                                ////A unique string that identifies the device. (Video capture devices only.)
                                //property.Read("DevicePath", out var devicePath, null);

                                ////The identifier for an audio capture device. (Audio capture devices only.)
                                //property.Read("WaveInID", out var waveInID, null);

                                hResult = property.Read("FriendlyName", out var friendlyName, null);

                                if (deviceName == friendlyName.ToString())
                                {
                                    iid = typeof(IBaseFilter).GUID;
                                    moniker.BindToObject(null, null, ref iid, out var filter);
                                    foundFilter = (IBaseFilter)filter;

                                    break;
                                }
                            }
                        }
                        finally
                        {
                            if (moniker != null)
                            {
                                Marshal.ReleaseComObject(moniker);
                            }
                        }
                    }
                }
            }
            finally
            {
                if (classEnum != null)
                {
                    Marshal.ReleaseComObject(classEnum);
                }
            }

            return(foundFilter);
        }
Esempio n. 19
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)
            {
                var currentProc = Process.GetCurrentProcess().MainModule.FileName;
                if (StringComparer.OrdinalIgnoreCase.Equals(
                        Path.GetFileName(currentProc), "vstest.executionengine.x86.exe"))
                {
                    var baseDir          = Path.GetDirectoryName(currentProc);
                    var 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";
            }

            var    progId        = $"!{prefix}.DTE.15.0:{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];
                uint numberFetched = 0;
                while (enumMonikers.Next(1, moniker, out numberFetched) == 0)
                {
                    var    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 (StringComparer.Ordinal.Equals(name, progId))
                    {
                        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);
        }
Esempio n. 20
0
        private static object GetDTE(int processId)
        {
            object runningObject = null;

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

            var names = new List <string>();

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

                    names.Add(name);

                    if (!string.IsNullOrEmpty(name) && name.StartsWith("!VisualStudio.DTE.") && name.EndsWith(processId.ToString()))
                    {
                        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);
        }
Esempio n. 21
0
 void IMoniker.Enum(bool fForward, out IEnumMoniker ppenumMoniker)
 {
     throw new Exception("The method or operation is not implemented.");
 }
Esempio n. 22
0
        public AudioEncoderCollection()
        {
            ICreateDevEnum deviceEnumerator = null;

            try
            {
                deviceEnumerator = (ICreateDevEnum) new CreateDevEnum();

                IEnumMoniker monikerEnum = null;

                try
                {
                    int hr =
                        deviceEnumerator.CreateClassEnumerator(FilterGraphTools.CLSID_AudioCompressorCategory,
                                                               out monikerEnum, CDef.None);
                    DsError.ThrowExceptionForHR(hr);

                    IMoniker[] monikers = new IMoniker[1];

                    while (true)
                    {
                        try
                        {
                            hr = monikerEnum.Next(1, monikers, IntPtr.Zero);

                            DsError.ThrowExceptionForHR(hr);

                            object bag;

                            Guid id = FilterGraphTools.IID_IPropertyBag;

                            if (monikers[0] == null)
                            {
                                break;
                            }

                            monikers[0].BindToStorage(null, null, ref id, out bag);

                            IPropertyBag propertyBag = (IPropertyBag)bag;

                            Marshal.ReleaseComObject(propertyBag);

                            object variantName;
                            hr = propertyBag.Read("FriendlyName", out variantName, null);
                            DsError.ThrowExceptionForHR(hr);

                            string friendlyName = Convert.ToString(variantName);

                            Guid id2 = FilterGraphTools.IID_IBaseFilter;

                            object filter;

                            monikers[0].BindToObject(null, null, ref id2, out filter);

                            if (filter != null)
                            {
                                _encoders.Add(new AudioEncoder(friendlyName, (IBaseFilter)filter));
                            }
                        }
                        finally
                        {
                            if (monikers[0] != null)
                            {
                                Marshal.ReleaseComObject(monikers[0]);
                            }
                        }
                    }
                }
                finally
                {
                    if (monikerEnum != null)
                    {
                        Marshal.ReleaseComObject(monikerEnum);
                    }
                }
            }
            finally
            {
                if (deviceEnumerator != null)
                {
                    Marshal.ReleaseComObject(deviceEnumerator);
                }
            }
        }
Esempio n. 23
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
                    {
                        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
                    }

                    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);
        }
Esempio n. 24
0
        /// <summary>
        /// Create an instance of the filter.
        /// </summary>
        ///
        /// <param name="filterMoniker">Filter's moniker string.</param>
        ///
        /// <returns>Returns filter's object, which implements <b>IBaseFilter</b> interface.</returns>
        ///
        /// <remarks>The returned filter's object should be released using <b>Marshal.ReleaseComObject()</b>.</remarks>
        ///
        public static object CreateFilter(string filterMoniker)
        {
            object         filterObject = null;
            object         comObj       = null;
            ICreateDevEnum enumDev      = null;
            IEnumMoniker   enumMon      = null;

            IMoniker[] devMon = new IMoniker[1];
            int        hr;

            try
            {
                // Get the system device enumerator
                Type srvType = Type.GetTypeFromCLSID(Clsid.SystemDeviceEnum);
                if (srvType == null)
                {
                    throw new ApplicationException("Failed creating device enumerator");
                }

                // create device enumerator
                comObj  = Activator.CreateInstance(srvType);
                enumDev = (ICreateDevEnum)comObj;

                // Create an enumerator to find filters of specified category

                Guid cat = FilterCategory.VideoInputDevice;
                hr = enumDev.CreateClassEnumerator(ref cat, out enumMon, 0);
                if (hr != 0)
                {
                    throw new ApplicationException("No devices of the category");
                }

                // Collect all filters
                IntPtr n = IntPtr.Zero;
                while (true)
                {
                    // Get next filter
                    hr = enumMon.Next(1, devMon, n);
                    if ((hr != 0) || (devMon[0] == null))
                    {
                        break;
                    }

                    // Add the filter
                    FilterInfo filter = new FilterInfo(devMon[0]);
                    if (filter.MonikerString == filterMoniker)
                    {
                        Guid filterId = typeof(IBaseFilter).GUID;
                        devMon[0].BindToObject(null, null, ref filterId, out filterObject);
                        break;
                    }

                    // Release COM object
                    Marshal.ReleaseComObject(devMon[0]);
                    devMon[0] = null;
                }
            }
            catch
            {
            }
            finally
            {
                // release all COM objects
                enumDev = null;
                if (comObj != null)
                {
                    Marshal.ReleaseComObject(comObj);
                    comObj = null;
                }
                if (enumMon != null)
                {
                    Marshal.ReleaseComObject(enumMon);
                    enumMon = null;
                }
                if (devMon[0] != null)
                {
                    Marshal.ReleaseComObject(devMon[0]);
                    devMon[0] = null;
                }
            }
            return(filterObject);
            //// filter's object
            //object filterObject = null;
            //// bind context and moniker objects
            //IBindCtx bindCtx = null;
            //IMoniker moniker = null;

            //int n = 0;

            //// create bind context
            //if ( Win32.CreateBindCtx( 0, out bindCtx ) == 0 )
            //{
            //    // convert moniker`s string to a moniker
            //    if ( Win32.MkParseDisplayName( bindCtx, filterMoniker, ref n, out moniker ) == 0 )
            //    {
            //        // get device base filter
            //        Guid filterId = typeof( IBaseFilter ).GUID;
            //        moniker.BindToObject( null, null, ref filterId, out filterObject );

            //        Marshal.ReleaseComObject( moniker );
            //    }
            //    Marshal.ReleaseComObject( bindCtx );
            //}
            //return filterObject;
        }
Esempio n. 25
0
        private void CollectFilters(Guid category)
        {
            object         comObj  = null;
            ICreateDevEnum enumDev = null;
            IEnumMoniker   enumMon = null;

            IMoniker[] devMon = new IMoniker[1];
            int        hr;

            try
            {
                // Get the system device enumerator
                Type srvType = Type.GetTypeFromCLSID(Clsid.SystemDeviceEnum);
                if (srvType == null)
                {
                    throw new ApplicationException("Failed creating device enumerator");
                }

                // create device enumerator
                comObj  = Activator.CreateInstance(srvType);
                enumDev = (ICreateDevEnum)comObj;

                // Create an enumerator to find filters of specified category
                hr = enumDev.CreateClassEnumerator(ref category, out enumMon, 0);
                if (hr != 0)
                {
                    throw new ApplicationException("No devices of the category");
                }

                // Collect all filters
                IntPtr n = IntPtr.Zero;
                while (true)
                {
                    // Get next filter
                    hr = enumMon.Next(1, devMon, n);
                    if ((hr != 0) || (devMon[0] == null))
                    {
                        break;
                    }

                    // Add the filter
                    FilterInfo filter = new FilterInfo(devMon[0]);
                    this.Add(filter);

                    // Release COM object
                    Marshal.ReleaseComObject(devMon[0]);
                    devMon[0] = null;
                }

                // Sort the collection
                this.Sort();
            }
            catch
            {
            }
            finally
            {
                // release all COM objects
                enumDev = null;
                if (comObj != null)
                {
                    Marshal.ReleaseComObject(comObj);
                    comObj = null;
                }
                if (enumMon != null)
                {
                    Marshal.ReleaseComObject(enumMon);
                    enumMon = null;
                }
                if (devMon[0] != null)
                {
                    Marshal.ReleaseComObject(devMon[0]);
                    devMon[0] = null;
                }
            }
        }
Esempio n. 26
0
        internal static DTE2 GetDTE()
        {
            string progId        = @"^!VisualStudio\.DTE\.\d{2}\.\d\:" + System.Diagnostics.Process.GetCurrentProcess().Id + "$";
            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) && Regex.IsMatch(name, progId))
                    {
                        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);
        }
Esempio n. 27
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);
        }
Esempio n. 28
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);
                }
            }
        }
Esempio n. 29
0
        public static List<RunningObjectTableComponentInfo> GetComponentsFromROT()
        {
            IEnumMoniker monikerList = null;
            IRunningObjectTable runningObjectTable = null;
            List<RunningObjectTableComponentInfo> resultList = new List<RunningObjectTableComponentInfo>();
            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)
                {
                    // create binding object
                    IBindCtx bindInfo;
                    CreateBindCtx(0, out bindInfo);

                    // query com proxy info      
                    object comInstance = null;
                    runningObjectTable.GetObject(monikerContainer[0], out comInstance);

                    string ppszDisplayName;
                    try { monikerContainer[0].GetDisplayName(bindInfo, null, out ppszDisplayName); }
                    catch { ppszDisplayName = ""; }

                    Guid pClassID;
                    try { monikerContainer[0].GetClassID(out pClassID); }
                    catch { pClassID = Guid.Empty; }
                    
                    System.Runtime.InteropServices.ComTypes.FILETIME pLastChangedFileTime;
                    try { runningObjectTable.GetTimeOfLastChange(monikerContainer[0], out pLastChangedFileTime);}
                    catch { pLastChangedFileTime = new System.Runtime.InteropServices.ComTypes.FILETIME(); }
                    
                    long pcbSize;
                    try { monikerContainer[0].GetSizeMax(out pcbSize);}
                    catch { pcbSize = 0;}
                    
                    
                    Boolean IsDirty;
                    try {IsDirty = (monikerContainer[0].IsDirty() == 0); }
                    catch {IsDirty = false;}

                    Boolean IsRunning;
                    try {IsRunning = (runningObjectTable.IsRunning(monikerContainer[0]) == 0); }
                    catch {IsRunning = false;}

                    // creating the unbound object to hold the Data out of the current component IMoniker
                    RunningObjectTableComponentInfo ROTComponent = new RunningObjectTableComponentInfo(
                        ppszDisplayName,
                        pClassID,
                        ConvertFromFILETIME(pLastChangedFileTime),
                        pcbSize,
                        TypeDescriptor.GetComponentName(comInstance, false),
                        TypeDescriptor.GetClassName(comInstance),
                        IsRunning,
                        IsDirty
                    );

                    resultList.Add(ROTComponent);

                    // clean up and release object 
                    Marshal.ReleaseComObject(comInstance);
                    Marshal.ReleaseComObject(bindInfo);
                }

                // not running
                return resultList;
            }
            finally
            {
                // release proxies
                if (runningObjectTable != null)
                    Marshal.ReleaseComObject(runningObjectTable);
                if (monikerList != null)
                    Marshal.ReleaseComObject(monikerList);
            }
        }
        private void CollectFilters(Guid category)
        {
            object         comObj  = null;
            ICreateDevEnum enumDev = null;
            IEnumMoniker   enumMon = null;

            IMoniker[] devMon = new IMoniker[1];
            int        hr;

            try
            {
                Type srvType = Type.GetTypeFromCLSID(Clsid.SystemDeviceEnum);
                if (srvType == null)
                {
                    throw new ApplicationException("Failed creating device enumerator");
                }


                comObj  = Activator.CreateInstance(srvType);
                enumDev = (ICreateDevEnum)comObj;


                hr = enumDev.CreateClassEnumerator(ref category, out enumMon, 0);
                if (hr != 0)
                {
                    throw new ApplicationException("No devices of the category");
                }


                IntPtr n = IntPtr.Zero;
                while (true)
                {
                    hr = enumMon.Next(1, devMon, n);
                    if ((hr != 0) || (devMon[0] == null))
                    {
                        break;
                    }


                    FilterInfo filter = new FilterInfo(devMon[0]);
                    InnerList.Add(filter);


                    Marshal.ReleaseComObject(devMon[0]);
                    devMon[0] = null;
                }


                InnerList.Sort( );
            }
            catch
            {
            }
            finally
            {
                enumDev = null;
                if (comObj != null)
                {
                    Marshal.ReleaseComObject(comObj);
                    comObj = null;
                }
                if (enumMon != null)
                {
                    Marshal.ReleaseComObject(enumMon);
                    enumMon = null;
                }
                if (devMon[0] != null)
                {
                    Marshal.ReleaseComObject(devMon[0]);
                    devMon[0] = null;
                }
            }
        }
 void IMoniker.Enum(bool fForward, out IEnumMoniker ppenumMoniker)
 {
     throw new Exception("The method or operation is not implemented.");
 }
Esempio n. 32
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);
        }
 void IMoniker.Enum(bool fForward, out IEnumMoniker ppenumMoniker)
 {
     throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotImplementedException());
 }
Esempio n. 34
0
        /// <summary>
        /// Returns all running com proxies + add. informations 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 informations</returns>
        public static IDisposableEnumeration <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);
                        Marshal.ReleaseComObject(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)
                {
                    Marshal.ReleaseComObject(runningObjectTable);
                }
                if (monikerList != null)
                {
                    Marshal.ReleaseComObject(monikerList);
                }
            }
        }