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); }
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); }
public static bool GetDevicesOfCat(Guid cat, out ArrayList devs) { devs = null; int hr; object comObj = null; ICreateDevEnum enumDev = null; IEnumMoniker enumMon = null; IMoniker[] mon = new IMoniker[1]; try { Type srvType = Type.GetTypeFromCLSID(Clsid.SystemDeviceEnum); if (srvType == null) { throw new NotImplementedException("System Device Enumerator"); } comObj = Activator.CreateInstance(srvType); enumDev = (ICreateDevEnum)comObj; hr = enumDev.CreateClassEnumerator(ref cat, out enumMon, 0); if (hr != 0) { throw new NotSupportedException("No devices of the category"); } IntPtr f = IntPtr.Zero; int count = 0; do { hr = enumMon.Next(1, mon, f); if ((hr != 0) || (mon[0] == null)) { break; } DsDevice 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 ex) { 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; } }
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); }
// 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); }
// Collect filters of specified category 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]); InnerList.Add(filter); // Release COM object Marshal.ReleaseComObject(devMon[0]); devMon[0] = null; } // Sort the collection InnerList.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; } } }
/// <summary> /// returns all running com proxies from the running object table there matched with the input parameters /// </summary> /// <param name="componentName">component name, for example Excel</param> /// <param name="className">class name, for example Application</param> /// <returns>COM proxy list</returns> public static List <object> GetActiveProxiesFromROT(string componentName, string className) { IEnumMoniker monikerList = null; IRunningObjectTable runningObjectTable = null; List <object> resultList = new List <object>(); try { // query table and returns null if no objects 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); // get class name and component name string name = TypeDescriptor.GetClassName(comInstance); string component = TypeDescriptor.GetComponentName(comInstance, false); // match for equal and add to list bool componentNameEqual = (componentName.Equals(component, StringComparison.InvariantCultureIgnoreCase)); bool classNameEqual = (className.Equals(name, StringComparison.InvariantCultureIgnoreCase)); if (componentNameEqual && classNameEqual) { resultList.Add(comInstance); } else { componentNameEqual = ((_ballmersPlace + componentName).Equals(component, StringComparison.InvariantCultureIgnoreCase)); if (componentNameEqual && classNameEqual) { resultList.Add(comInstance); } else { if (comInstance.GetType().IsCOMObject) { Marshal.ReleaseComObject(comInstance); } } } if (bindInfo.GetType().IsCOMObject) { Marshal.ReleaseComObject(bindInfo); } } return(resultList); } finally { // release proxies if (runningObjectTable != null) { Marshal.ReleaseComObject(runningObjectTable); } if (monikerList != null) { Marshal.ReleaseComObject(monikerList); } } }
/// <summary> /// returns a running com proxy from the running object table. the method takes the first proxy there matched with the input parameters. /// WARNING: the method returns always the first com proxy from the running object table if multiple (match) proxies exists. /// </summary> /// <param name="componentName">component name, for example Excel</param> /// <param name="className">class name, for example Application</param> /// <param name="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); } } }
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> /// Gets the DTE object from any devenv process. /// </summary> /// <param name="processId"> /// <returns> /// Retrieved DTE object or <see langword="null"> if not found. /// </see></returns> private 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. } Regex 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 DTE); }
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); }
/// <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); } } }
/// <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); } } }
/// <summary> /// Returns all running com proxies from the running object table there matched with the input parameters /// WARNING: the method returns always the first com proxy from the running object table if multiple (match) proxies exists. /// </summary> /// <param name="componentName">component name, for example Excel, null is a wildcard </param> /// <param name="className">class name, for example Application, null is a wildcard </param> /// <returns>COM proxy enumerator</returns> public static IDisposableEnumeration GetActiveProxies(string componentName, string className) { IEnumMoniker monikerList = null; IRunningObjectTable runningObjectTable = null; Misc.DisposableObjectList resultList = new Misc.DisposableObjectList(); try { // query table and returns null if no objects running if (GetRunningObjectTable(0, out runningObjectTable) != 0 || runningObjectTable == null) { return(null); } // query moniker & reset runningObjectTable.EnumRunning(out monikerList); monikerList.Reset(); IMoniker[] monikerContainer = new IMoniker[1]; IntPtr pointerFetchedMonikers = IntPtr.Zero; // fetch all moniker while (monikerList.Next(1, monikerContainer, pointerFetchedMonikers) == 0) { // query com proxy info object comInstance = null; runningObjectTable.GetObject(monikerContainer[0], out comInstance); if (null == comInstance) { continue; } // get class name and component name string name = TypeDescriptor.GetClassName(comInstance); string component = TypeDescriptor.GetComponentName(comInstance, false); // match for equal and add to list bool componentNameEqual = String.IsNullOrWhiteSpace(component) ? true : (componentName.Equals(component, StringComparison.InvariantCultureIgnoreCase)); bool classNameEqual = String.IsNullOrWhiteSpace(className) ? true : (className.Equals(name, StringComparison.InvariantCultureIgnoreCase)); if (componentNameEqual && classNameEqual) { resultList.Add(comInstance); } else { componentNameEqual = ((_ballmersPlace + componentName).Equals(component, StringComparison.InvariantCultureIgnoreCase)); if (componentNameEqual && classNameEqual) { resultList.Add(comInstance); } else { if (comInstance.GetType().IsCOMObject) { Marshal.ReleaseComObject(comInstance); } } } } 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); } } }
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); } } }
/// <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); }
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); }
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)); }
/// <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 ); } }
protected IMoniker getAnyMoniker() #endif #endif { Guid category = FilterCategory.VideoCompressorCategory; 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 { // Get the system device enumerator #if DSHOWNET 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 // Get the system device enumerator enumDev = (ICreateDevEnum) new DirectShowLib.CreateDevEnum(); // Create an enumerator to find filters in category hr = enumDev.CreateClassEnumerator(category, out enumMon, CDef.None); #endif if (hr != 0) { throw new NotSupportedException("No devices of the category"); } // Get first filter #if DSHOWNET IntPtr f = IntPtr.Zero; hr = enumMon.Next(1, mon, f); #else #if VS2003 int f; hr = enumMon.Next(1, mon, out f); #else IntPtr f = IntPtr.Zero; hr = enumMon.Next(1, mon, f); #endif #endif if ((hr != 0)) { mon[0] = null; } return(mon[0]); } finally { enumDev = null; if (enumMon != null) { Marshal.ReleaseComObject(enumMon); } enumMon = null; if (comObj != null) { Marshal.ReleaseComObject(comObj); } comObj = null; } }