System.Runtime.InteropServices.Marshal.ReleaseComObject(object)

Here are the examples of the csharp api System.Runtime.InteropServices.Marshal.ReleaseComObject(object) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

755 Examples 7

19 Source : VistaFileSaveDialog.cs
with GNU General Public License v3.0
from 0xC0000054

protected override bool RunDialog(IntPtr hwndOwner)
        {
            if (Application.OleRequired() != ApartmentState.STA)
            {
                throw new ThreadStateException("The calling thread must be STA.");
            }

            bool result = false;

            NativeInterfaces.IFileSaveDialog dialog = null;

            try
            {
                dialog = CreateDialog();

                OnBeforeShow(dialog);

                FileSaveDialogEvents dialogEvents = new FileSaveDialogEvents(this);
                uint eventCookie;
                dialog.Advise(dialogEvents, out eventCookie);
                try
                {
                    result = dialog.Show(hwndOwner) == NativeConstants.S_OK;
                }
                finally
                {
                    dialog.Unadvise(eventCookie);
                    // Prevent the IFileDialogEvents interface from being collected while the dialog is running.
                    GC.KeepAlive(dialogEvents);
                }
            }
            finally
            {
                if (dialog != null)
                {
                    Marshal.ReleaseComObject(dialog);
                }
            }

            return result;
        }

19 Source : VistaFileSaveDialog.cs
with GNU General Public License v3.0
from 0xC0000054

private bool HandleFileOk(NativeInterfaces.IFileDialog pfd)
        {
            bool result = false;

            NativeInterfaces.IShellItem resultShellItem = null;
            try
            {
                pfd.GetResult(out resultShellItem);

                string path;
                resultShellItem.GetDisplayName(NativeEnums.SIGDN.SIGDN_FILESYSPATH, out path);

                fileName = path;
                result = true;
            }
            finally
            {
                if (resultShellItem != null)
                {
                    Marshal.ReleaseComObject(resultShellItem);
                }
            }

            return result;
        }

19 Source : VistaFolderBrowserDialog.cs
with GNU General Public License v3.0
from 0xC0000054

private void OnBeforeShow(NativeInterfaces.IFileOpenDialog dialog)
        {
            SetDialogOptions(dialog);

            if (!string.IsNullOrEmpty(replacedle))
            {
                dialog.Setreplacedle(replacedle);
            }

            if (!string.IsNullOrEmpty(defaultFolder))
            {
                NativeInterfaces.IShellItem defaultFolderShellItem = null;

                try
                {
                    if (CreateShellItemFromPath(defaultFolder, out defaultFolderShellItem))
                    {
                        dialog.SetDefaultFolder(defaultFolderShellItem);
                    }
                }
                finally
                {
                    if (defaultFolderShellItem != null)
                    {
                        Marshal.ReleaseComObject(defaultFolderShellItem);
                    }
                }
            }

            if (!string.IsNullOrEmpty(selectedPath))
            {
                dialog.SetFileName(selectedPath);
            }
        }

19 Source : VistaFolderBrowserDialog.cs
with GNU General Public License v3.0
from 0xC0000054

protected override bool RunDialog(IntPtr hwndOwner)
        {
            if (Application.OleRequired() != ApartmentState.STA)
            {
                throw new ThreadStateException("The calling thread must be STA.");
            }

            bool result = false;

            NativeInterfaces.IFileOpenDialog dialog = null;

            try
            {
                dialog = CreateDialog();

                OnBeforeShow(dialog);

                FolderBrowserDialogEvents dialogEvents = new FolderBrowserDialogEvents(this);
                uint eventCookie;
                dialog.Advise(dialogEvents, out eventCookie);
                try
                {
                    result = dialog.Show(hwndOwner) == NativeConstants.S_OK;
                }
                finally
                {
                    dialog.Unadvise(eventCookie);
                    // Prevent the IFileDialogEvents interface from being collected while the dialog is running.
                    GC.KeepAlive(dialogEvents);
                }
            }
            finally
            {
                if (dialog != null)
                {
                    Marshal.ReleaseComObject(dialog);
                }
            }

            return result;
        }

19 Source : VistaFolderBrowserDialog.cs
with GNU General Public License v3.0
from 0xC0000054

private bool HandleFileOk(NativeInterfaces.IFileDialog pfd)
        {
            bool result = false;

            NativeInterfaces.IShellItem resultShellItem = null;
            try
            {
                pfd.GetResult(out resultShellItem);

                string path;
                resultShellItem.GetDisplayName(NativeEnums.SIGDN.SIGDN_FILESYSPATH, out path);

                selectedPath = path;
                result = true;
            }
            finally
            {
                if (resultShellItem != null)
                {
                    Marshal.ReleaseComObject(resultShellItem);
                }
            }

            return result;
        }

19 Source : Client.cs
with BSD 3-Clause "New" or "Revised" License
from 0xthirteen

private void RdpConnectionOnOnLogonError(object sender, IMsTscAxEvents_OnLogonErrorEvent e)
        {
            LogonErrorCode = e.lError;
            var errorstatus = Enum.GetName(typeof(LogonErrors), (uint)LogonErrorCode);
            Console.WriteLine("[-] Logon Error           :  {0} - {1}", LogonErrorCode, errorstatus);
            Thread.Sleep(1000);

            if(LogonErrorCode == -5 && takeover == true)
            {
                // it doesn't go to the logon event, so this has to be done here
                var rdpSession = (AxMsRdpClient9NotSafeForScripting)sender;
                Thread.Sleep(1000);
                keydata = (IMsRdpClientNonScriptable)rdpSession.GetOcx();
                Console.WriteLine("[+] Another user is logged on, asking to take over session");
                SendElement("Tab");
                Thread.Sleep(500);
                SendElement("Enter+down");
                Thread.Sleep(500);
                SendElement("Enter+up");
                Thread.Sleep(500);
                Console.WriteLine("[+] Sleeping for 30 seconds");
                Task.Delay(31000).GetAwaiter().GetResult();
                Marshal.ReleaseComObject(rdpSession);
                Marshal.ReleaseComObject(keydata);
            }
            else if (LogonErrorCode != -2)
            {
                Environment.Exit(0);
            }
        }

19 Source : Converters.cs
with MIT License
from adyanth

private static IntPtr GetHBitmap(string fileName, int width, int height, ThumbnailOptions options)
        {
            var shellItem2Guid = new Guid(IShellItem2Guid);
            var retCode =
                SHCreateItemFromParsingName(fileName, IntPtr.Zero, ref shellItem2Guid, out var nativeShellItem);

            if (retCode != 0)
                return IntPtr.Zero;

            var nativeSize = new NativeSize
            {
                Width = width,
                Height = height
            };

            var hr = ((IShellItemImageFactory)nativeShellItem).GetImage(nativeSize, options, out var hBitmap);

            Marshal.ReleaseComObject(nativeShellItem);

            return hr == HResult.Ok ? hBitmap : IntPtr.Zero;
        }

19 Source : OpenFolderDialog.cs
with GNU Affero General Public License v3.0
from aianlinb

public bool? ShowDialog(Window owner = null)
        {
            ;
            IntPtr hwndOwner = owner != null ? new WindowInteropHelper(owner).Handle : Process.GetCurrentProcess().MainWindowHandle;
            IFileOpenDialog dialog = (IFileOpenDialog)new FileOpenDialog();
            try
            {
                IShellItem item;
                if (!string.IsNullOrEmpty(DirectoryPath))
                {
                    uint atts = 0;
                    if (SHILCreateFromPath(DirectoryPath, out IntPtr idl, ref atts) == 0)
                        if (SHCreateShellItem(IntPtr.Zero, IntPtr.Zero, idl, out item) == 0)
                            dialog.SetFolder(item);
                }
                dialog.SetOptions(FOS.FOS_PICKFOLDERS | FOS.FOS_FORCEFILESYSTEM);
                uint hr = dialog.Show(hwndOwner);
                if (hr == ERROR_CANCELLED)
                    return false;
                if (hr != 0)
                    return null;
                dialog.GetResult(out item);
                item.GetDisplayName(SIGDN.SIGDN_FILESYSPATH, out string path);
                DirectoryPath = path;
                return true;
            }
            finally
            {
                Marshal.ReleaseComObject(dialog);
            }
        }

19 Source : OpenFolderDialog.cs
with GNU Affero General Public License v3.0
from aianlinb

public bool? ShowDialog(Window owner = null) {
        ;
        IntPtr hwndOwner = owner != null ? new WindowInteropHelper(owner).Handle : Process.GetCurrentProcess().MainWindowHandle;
        IFileOpenDialog dialog = (IFileOpenDialog)new FileOpenDialog();
        try {
            IShellItem item;
            if (!string.IsNullOrEmpty(DirectoryPath)) {
                uint atts = 0;
                if (SHILCreateFromPath(DirectoryPath, out IntPtr idl, ref atts) == 0)
                    if (SHCreateShellItem(IntPtr.Zero, IntPtr.Zero, idl, out item) == 0)
                        dialog.SetFolder(item);
            }
            dialog.SetOptions(FOS.FOS_PICKFOLDERS | FOS.FOS_FORCEFILESYSTEM);
            uint hr = dialog.Show(hwndOwner);
            if (hr == ERROR_CANCELLED)
                return false;
            if (hr != 0)
                return null;
            dialog.GetResult(out item);
            item.GetDisplayName(SIGDN.SIGDN_FILESYSPATH, out string path);
            DirectoryPath = path;
            return true;
        } finally {
            Marshal.ReleaseComObject(dialog);
        }
    }

19 Source : AudioManager.cs
with MIT License
from AlbertMN

public static float GetMasterVolume() {
            IAudioEndpointVolume masterVol = null;
            try {
                masterVol = GetMasterVolumeObject();
                if (masterVol == null)
                    return -1;

                masterVol.GetMasterVolumeLevelScalar(out float volumeLevel);
                return volumeLevel * 100;
            } finally {
                if (masterVol != null)
                    Marshal.ReleaseComObject(masterVol);
            }
        }

19 Source : AudioManager.cs
with MIT License
from AlbertMN

public static bool GetMasterVolumeMute() {
            IAudioEndpointVolume masterVol = null;
            try {
                masterVol = GetMasterVolumeObject();
                if (masterVol == null)
                    return false;

                masterVol.GetMute(out bool isMuted);
                return isMuted;
            } finally {
                if (masterVol != null)
                    Marshal.ReleaseComObject(masterVol);
            }
        }

19 Source : AudioManager.cs
with MIT License
from AlbertMN

public static void SetMasterVolume(float newLevel) {
            IAudioEndpointVolume masterVol = null;
            try {
                masterVol = GetMasterVolumeObject();
                if (masterVol == null)
                    return;

                masterVol.SetMasterVolumeLevelScalar(newLevel / 100, Guid.Empty);
            } finally {
                if (masterVol != null)
                    Marshal.ReleaseComObject(masterVol);
            }
        }

19 Source : AudioManager.cs
with MIT License
from AlbertMN

public static float StepMasterVolume(float stepAmount) {
            IAudioEndpointVolume masterVol = null;
            try {
                masterVol = GetMasterVolumeObject();
                if (masterVol == null)
                    return -1;

                float stepAmountScaled = stepAmount / 100;

                // Get the level
                masterVol.GetMasterVolumeLevelScalar(out float volumeLevel);

                // Calculate the new level
                float newLevel = volumeLevel + stepAmountScaled;
                newLevel = Math.Min(1, newLevel);
                newLevel = Math.Max(0, newLevel);

                masterVol.SetMasterVolumeLevelScalar(newLevel, Guid.Empty);

                // Return the new volume level that was set
                return newLevel * 100;
            } finally {
                if (masterVol != null)
                    Marshal.ReleaseComObject(masterVol);
            }
        }

19 Source : AudioManager.cs
with MIT License
from AlbertMN

public static void SetMasterVolumeMute(bool isMuted) {
            IAudioEndpointVolume masterVol = null;
            try {
                masterVol = GetMasterVolumeObject();
                if (masterVol == null)
                    return;

                masterVol.SetMute(isMuted, Guid.Empty);
            } finally {
                if (masterVol != null)
                    Marshal.ReleaseComObject(masterVol);
            }
        }

19 Source : AudioManager.cs
with MIT License
from AlbertMN

public static bool ToggleMasterVolumeMute() {
            IAudioEndpointVolume masterVol = null;
            try {
                masterVol = GetMasterVolumeObject();
                if (masterVol == null)
                    return false;

                masterVol.GetMute(out bool isMuted);
                masterVol.SetMute(!isMuted, Guid.Empty);

                return !isMuted;
            } finally {
                if (masterVol != null)
                    Marshal.ReleaseComObject(masterVol);
            }
        }

19 Source : AudioManager.cs
with MIT License
from AlbertMN

private static IAudioEndpointVolume GetMasterVolumeObject() {
            IMMDeviceEnumerator deviceEnumerator = null;
            IMMDevice speakers = null;
            try {
                deviceEnumerator = (IMMDeviceEnumerator)(new MMDeviceEnumerator());
                deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia, out speakers);

                Guid IID_IAudioEndpointVolume = typeof(IAudioEndpointVolume).GUID;
                speakers.Activate(ref IID_IAudioEndpointVolume, 0, IntPtr.Zero, out object o);
                IAudioEndpointVolume masterVol = (IAudioEndpointVolume)o;

                return masterVol;
            } finally {
                if (speakers != null) Marshal.ReleaseComObject(speakers);
                if (deviceEnumerator != null) Marshal.ReleaseComObject(deviceEnumerator);
            }
        }

19 Source : AudioManager.cs
with MIT License
from AlbertMN

public static float? GetApplicationVolume(int pid) {
            ISimpleAudioVolume volume = GetVolumeObject(pid);
            if (volume == null)
                return null;

            volume.GetMasterVolume(out float level);
            Marshal.ReleaseComObject(volume);
            return level * 100;
        }

19 Source : AudioManager.cs
with MIT License
from AlbertMN

public static bool? GetApplicationMute(int pid) {
            ISimpleAudioVolume volume = GetVolumeObject(pid);
            if (volume == null)
                return null;

            volume.GetMute(out bool mute);
            Marshal.ReleaseComObject(volume);
            return mute;
        }

19 Source : AudioManager.cs
with MIT License
from AlbertMN

public static void SetApplicationVolume(int pid, float level) {
            ISimpleAudioVolume volume = GetVolumeObject(pid);
            if (volume == null)
                return;

            Guid guid = Guid.Empty;
            volume.SetMasterVolume(level / 100, ref guid);
            Marshal.ReleaseComObject(volume);
        }

19 Source : AudioManager.cs
with MIT License
from AlbertMN

public static void SetApplicationMute(int pid, bool mute) {
            ISimpleAudioVolume volume = GetVolumeObject(pid);
            if (volume == null)
                return;

            Guid guid = Guid.Empty;
            volume.SetMute(mute, ref guid);
            Marshal.ReleaseComObject(volume);
        }

19 Source : AudioManager.cs
with MIT License
from AlbertMN

private static ISimpleAudioVolume GetVolumeObject(int pid) {
            IMMDeviceEnumerator deviceEnumerator = null;
            IAudioSessionEnumerator sessionEnumerator = null;
            IAudioSessionManager2 mgr = null;
            IMMDevice speakers = null;
            try {
                // get the speakers (1st render + multimedia) device
                deviceEnumerator = (IMMDeviceEnumerator)(new MMDeviceEnumerator());
                deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia, out speakers);

                // activate the session manager. we need the enumerator
                Guid IID_IAudioSessionManager2 = typeof(IAudioSessionManager2).GUID;
                speakers.Activate(ref IID_IAudioSessionManager2, 0, IntPtr.Zero, out object o);
                mgr = (IAudioSessionManager2)o;

                // enumerate sessions for on this device
                mgr.GetSessionEnumerator(out sessionEnumerator);
                sessionEnumerator.GetCount(out int count);

                // search for an audio session with the required process-id
                ISimpleAudioVolume volumeControl = null;
                for (int i = 0; i < count; ++i) {
                    IAudioSessionControl2 ctl = null;
                    try {
                        sessionEnumerator.GetSession(i, out ctl);

                        // NOTE: we could also use the app name from ctl.GetDisplayName()
                        ctl.GetProcessId(out int cpid);

                        if (cpid == pid) {
                            volumeControl = ctl as ISimpleAudioVolume;
                            break;
                        }
                    } finally {
                        //if (ctl != null) Marshal.ReleaseComObject(ctl);
                    }
                }

                return volumeControl;
            } finally {
                if (sessionEnumerator != null) Marshal.ReleaseComObject(sessionEnumerator);
                if (mgr != null) Marshal.ReleaseComObject(mgr);
                if (speakers != null) Marshal.ReleaseComObject(speakers);
                if (deviceEnumerator != null) Marshal.ReleaseComObject(deviceEnumerator);
            }
        }

19 Source : AppDomainHelper.cs
with GNU General Public License v3.0
from Albo1125

public static IList<AppDomain> GetAppDomains()
        {
            IList<AppDomain> domains = new List<AppDomain>();
            IntPtr enumHandle = IntPtr.Zero;
            ICorRuntimeHost host = new CorRuntimeHost();

            try
            {
                host.EnumDomains(out enumHandle);
                while (true)
                {
                    object domain;
                    host.NextDomain(enumHandle, out domain);
                    if (domain == null) break;
                    AppDomain appDomain = (AppDomain)domain;
                    domains.Add(appDomain);
                }

                return domains;
            }
            finally
            {
                host.CloseEnum(enumHandle);
                Marshal.ReleaseComObject(host);
            }
        }

19 Source : ComPtr.cs
with MIT License
from AlexeiScherbakov

private void Free()
		{
			var ptr = Interlocked.Exchange<T>(ref _instance, null);
			if (null != ptr)
			{
				Marshal.ReleaseComObject(ptr);
			}
		}

19 Source : Windows10OnScreenKeyboardController.cs
with MIT License
from AlexeiScherbakov

private static void ShowByCom()
		{
			ITipInvocation instance = null;
			try
			{
				instance = (ITipInvocation)Activator.CreateInstance(ComTypes.TipInvocationType);
				var window = NativeMethods.GetDesktopWindow();
				instance.Toggle(NativeMethods.GetDesktopWindow());
			}
			finally
			{
				if (!ReferenceEquals(instance, null))
				{
					Marshal.ReleaseComObject(instance);
				}
			}
		}

19 Source : AnkhSvnPackage.SolutionProperties.cs
with Apache License 2.0
from AmpScm

public int LoadUserOptions(IVsSolutionPersistence pPersistence, uint grfLoadOpts)
        {
            if ((grfLoadOpts & (uint)__VSLOADUSEROPTS.LUO_OPENEDDSW) != 0)
            {
                return VSErr.S_OK; // We only know .suo; let's ignore old style projects
            }

            try
            {
                pPersistence.LoadPackageUserOpts(this, SccPendingChangeStream);
                pPersistence.LoadPackageUserOpts(this, SccExcludedStream);
                pPersistence.LoadPackageUserOpts(this, SccTranslateStream);

                return VSErr.S_OK;
            }
            catch (Exception ex)
            {
                IAnkhErrorHandler handler = GetService<IAnkhErrorHandler>();

                if (handler != null)
                    handler.OnError(ex);

                return Marshal.GetHRForException(ex);
            }
            finally
            {
                if (Marshal.IsComObject(pPersistence))
                    Marshal.ReleaseComObject(pPersistence); // See Package.cs from MPF for reason
            }
        }

19 Source : AnkhSvnPackage.SolutionProperties.cs
with Apache License 2.0
from AmpScm

public int ReadUserOptions([In] IStream pOptionsStream, [In] string pszKey)
        {
            try
            {
                using (ComStreamWrapper wrapper = new ComStreamWrapper(pOptionsStream, true))
                {
                    IAnkhSccService scc;
                    switch (pszKey)
                    {
                        case SccPendingChangeStream:
                            LoadPendingChanges(wrapper);
                            break;
                        case SccTranslateStream:
                            scc = GetService<IAnkhSccService>();
                            if (scc != null)
                                scc.SerializeSccTranslateData(wrapper, false);
                            break;
                        case SccExcludedStream:
                            scc = GetService<IAnkhSccService>();
                            if (scc != null)
                                scc.SerializeSccExcludeData(wrapper, false);
                            break;

                        default:
                            // TODO: Add support for some service api for our services
                            break;
                    }
                }
                return VSErr.S_OK; // Our data is in subversion properties
            }
            catch (EndOfStreamException)
            {
                // Ignore: Old version? Broken Solution File? (Common error)
                return VSErr.S_OK;;
            }
            catch (Exception ex)
            {
#if DEBUG
                IAnkhErrorHandler handler = GetService<IAnkhErrorHandler>();

                if (handler != null)
                    handler.OnError(ex);
#endif

                return VSErr.S_OK;
            }
            finally
            {
                if (Marshal.IsComObject(pOptionsStream))
                    Marshal.ReleaseComObject(pOptionsStream); // See Package.cs from MPF for reason
            }
        }

19 Source : AnkhSvnPackage.SolutionProperties.cs
with Apache License 2.0
from AmpScm

public int SaveUserOptions([In] IVsSolutionPersistence pPersistence)
        {
            try
            {
                IAnkhSccService scc = GetService<IAnkhSccService>();
                if (scc != null)
                {
                    if (!scc.IsActive)
                        return VSErr.S_OK;

                    pPersistence.SavePackageUserOpts(this, SccPendingChangeStream);
                    pPersistence.SavePackageUserOpts(this, SccExcludedStream);

                    if (scc.IsSolutionManaged)
                    {
                        pPersistence.SavePackageUserOpts(this, SccTranslateStream);
                    }
                }

                return VSErr.S_OK;
            }
            finally
            {
                if (Marshal.IsComObject(pPersistence))
                    Marshal.ReleaseComObject(pPersistence); // See Package.cs from MPF for reason
            }
        }

19 Source : AnkhSvnPackage.SolutionProperties.cs
with Apache License 2.0
from AmpScm

public int WriteUserOptions([In] IStream pOptionsStream, [In] string pszKey)
        {
            try
            {
                using (ComStreamWrapper wrapper = new ComStreamWrapper(pOptionsStream))
                {
                    IAnkhSccService scc;
                    switch (pszKey)
                    {
                        case SccPendingChangeStream:
                            WritePendingChanges(wrapper);
                            break;
                        case SccTranslateStream:
                            scc = GetService<IAnkhSccService>();
                            if (scc != null)
                                scc.SerializeSccTranslateData(wrapper, true);
                            break;
                        case SccExcludedStream:
                            scc = GetService<IAnkhSccService>();
                            if (scc != null)
                                scc.SerializeSccExcludeData(wrapper, true);
                            break;
                        default:
                            // TODO: Add support for some service api for our services
                            break;
                    }
                }

                return VSErr.S_OK;
            }
            finally
            {
                if (Marshal.IsComObject(pOptionsStream))
                    Marshal.ReleaseComObject(pOptionsStream); // See Package.cs from MPF for reason
            }
        }

19 Source : AnkhCodeWindowManager.cs
with Apache License 2.0
from AmpScm

public void Close()
        {
            object window = _window;
            _window = null;
            if (window != null)
            {
                if (_cookie != 0)
                {
                    ReleaseHook<IVsCodeWindowEvents>(window, _cookie);
                    _cookie = 0;
                }

                if (Marshal.IsComObject(window))
                    try
                    {
                        Marshal.ReleaseComObject(window);
                    }
                    catch { }
            }
        }

19 Source : AnkhColorizer.cs
with Apache License 2.0
from AmpScm

public void Close()
        {
            IVsTextLines lines = _lines;
            _lines = null;

            if (lines != null && Marshal.IsComObject(lines))
                try
                {
                    Marshal.ReleaseComObject(lines);
                }
                catch { }
        }

19 Source : ServedDevice.cs
with GNU General Public License v3.0
from ASCOMInitiative

private void BtnSetup_Click(object sender, EventArgs e)
        {
            // This device's ProgID is held in the variable progID so try and run its SetupDialog method
            ServerForm.LogMessage(0, 0, 0, "Setup", string.Format("Setup button pressed for device: {0}, ProgID: {1}", cmbDevice.Text, progID));

            try
            {
                // Get an instance of the driver from its ProgID and store this in a dynamic variable so that we can call its method directly
                Type ProgIdType = Type.GetTypeFromProgID(progID);
                //ServerForm.LogMessage(0, 0, 0, "Setup", string.Format("Found type: {0}", ProgIdType.Name));

                dynamic oDrv = Activator.CreateInstance(ProgIdType);
                //ServerForm.LogMessage(0, 0, 0, "Setup", "Created driver instance OK");

                try
                {
                    if (GetConnectdState(oDrv)) // Driver is connected and the Setup dialogue must be run with the device disconnected so ask whether we can disconnect it
                    {
                        DialogResult dialogResult = MessageBox.Show("Device is connected, OK to disconnect and run Setup?", "Disconnect Device?", MessageBoxButtons.OKCancel);
                        if (dialogResult == DialogResult.OK) // OK to disconnect and run setup dialogue
                        {
                            //ServerForm.LogMessage(0, 0, 0, "Setup", "User gave permission to disconnect device - setting Connected to false");
                            try { oDrv.Connected = false; } catch { }; // Set Connected to false ignoring errors
                            try { oDrv.Link = false; } catch { }; // Set Link to false (for IFocuserV1 devices) ignoring errors

                            int RemainingObjectCount = Marshal.FinalReleaseComObject(oDrv);
                            oDrv = null;
                            oDrv = Activator.CreateInstance(ProgIdType);

                            //ServerForm.LogMessage(0, 0, 0, "Setup", string.Format("Connected has bee set false and destroyed. New Connected value: {0}", oDrv.Connected));

                            //ServerForm.LogMessage(0, 0, 0, "Setup", "Device is now disconnected, calling SetupDialog method");
                            oDrv.SetupDialog();
                            //ServerForm.LogMessage(0, 0, 0, "Setup", "Completed SetupDialog method, setting Connected to true");

                            try
                            {
                                oDrv.Connected = true; // Try setting Connected to true
                            }
                            catch (Exception ex2) when (DeviceType.ToLowerInvariant() == "focuser")
                            {
                                // Connected failed so try Link in case this is an IFocuserV1 device
                                ServerForm.LogException(0, 0, 0, "Setup", $"Error setting Connected to true for focuser device {ProgID}, now trying Link for IFocuserV1 devices: \r\n{ex2}");
                                oDrv.Link = true;
                            }

                            //ServerForm.LogMessage(0, 0, 0, "Setup", "Driver is now Connected");
                        }
                        else // Not OK to disconnect so just do nothing and exit
                        {
                            ServerForm.LogMessage(0, 0, 0, "Setup", "User did not give permission to disconnect device - no action taken");
                        }
                    }
                    else // Driver is not connected 
                    {
                        //ServerForm.LogMessage(0, 0, 0, "Setup", "Device is disconnected so just calling SetupDialog method");
                        oDrv.SetupDialog();
                        //ServerForm.LogMessage(0, 0, 0, "Setup", "Completed SetupDialog method");

                        try { oDrv.Dispose(); } catch { }; // Dispose the driver if possible

                        // Release the COM object properly
                        try
                        {
                            //ServerForm.LogMessage(0, 0, 0, "Setup", "  Releasing COM object");
                            int LoopCount = 0;
                            int RemainingObjectCount = 0;

                            do
                            {
                                LoopCount += 1; // Increment the loop counter so that we don't go on for ever!
                                RemainingObjectCount = Marshal.ReleaseComObject(oDrv);
                                //ServerForm.LogMessage(0, 0, 0, "Setup", "  Remaining object count: " + RemainingObjectCount.ToString() + ", LoopCount: " + LoopCount);
                            } while ((RemainingObjectCount > 0) & (LoopCount < 20));
                        }
                        catch (Exception ex2)
                        {
                            ServerForm.LogMessage(0, 0, 0, "Setup", "  ReleaseComObject Exception: " + ex2.Message);
                        }

                        oDrv = null;
                    }
                }
                catch (Exception ex1)
                {
                    string errMsg = string.Format("Exception calling SetupDialog method: {0}", ex1.Message);
                    MessageBox.Show(errMsg);
                    ServerForm.LogMessage(0, 0, 0, "Setup", errMsg);
                    ServerForm.LogException(0, 0, 0, "Setup", ex1.ToString());
                }

            }
            catch (Exception ex)
            {
                string errMsg = string.Format("Exception creating driver {0} - {1}", progID, ex.Message);
                MessageBox.Show(errMsg);
                ServerForm.LogMessage(0, 0, 0, "Setup", errMsg);
                ServerForm.LogException(0, 0, 0, "Setup", ex.ToString());
            }
        }

19 Source : PathMeasure.cs
with Apache License 2.0
from ascora

internal void Dispose(bool disposing)
        {
            if (_geometry != null)
            {
                try
                {
                    if (disposing)
                    {
                        _geometry.Dispose();
                    }
                    else
                    {
                        if (System.Runtime.InteropServices.Marshal.IsComObject(_geometry))
                        {
                            System.Runtime.InteropServices.Marshal.ReleaseComObject(_geometry);
                        }
                    }
                }
                catch (Exception)
                {
                    // Ignore, but should not happen
                }
                finally
                {
                    _geometry = null;
                }
            }
        }

19 Source : PluginServer.cs
with MIT License
from Autodesk-Forge

public void Deactivate()
    {
      Trace.TraceInformation(": UpdateIPTParam: deactivating... ");

      // Release objects.
      Marshal.ReleaseComObject(_inventorServer);
      _inventorServer = null;

      GC.Collect();
      GC.WaitForPendingFinalizers();
    }

19 Source : DTEFinder.cs
with MIT License
from AVPolyakov

public static DTE2 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) &&
                        name.StartsWith($"!{ProgId}", StringComparison.Ordinal) && 
                        (!processId.HasValue || name.EndsWith($":{processId}", StringComparison.Ordinal)))
                    {
                        Marshal.ThrowExceptionForHR(rot.GetObject(runningObjectMoniker, out runningObject));
                        break;
                    }
                }
            }
            finally
            {
                if (enumMonikers != null)
                {
                    Marshal.ReleaseComObject(enumMonikers);
                }

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

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

            return (DTE2)runningObject;
        }

19 Source : Utilities.Windows.cs
with MIT License
from ay2015

[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")]
        public static void SafeRelease<T>(ref T comObject) where T : clreplaced
        {
            T t = comObject;
            comObject = default(T);
            if (null != t)
            {
                replacedert.IsTrue(Marshal.IsComObject(t));
                Marshal.ReleaseComObject(t);
            }
        }

19 Source : VirtualFileDataObject.cs
with MIT License
from Bassman2

public void SetData(short dataFormat, int index, FileDescriptor fileDescriptor, Action<Stream, FileDescriptor> streamData)
        {
            _dataObjects.Add(
                new DataObject
                {
                    FORMATETC = new FORMATETC
                    {
                        cfFormat = dataFormat,
                        ptd = IntPtr.Zero,
                        dwAspect = DVASPECT.DVASPECT_CONTENT,
                        lindex = index,
                        tymed = TYMED.TYMED_ISTREAM
                    },
                    GetData = () =>
                    {
                        // Create IStream for data
                        var ptr = IntPtr.Zero;
                        var iStream = NativeMethods.CreateStreamOnHGlobal(IntPtr.Zero, true);
                        if (streamData != null)
                        {
                            // Wrap in a .NET-friendly Stream and call provided code to fill it
                            using (var stream = new IStreamWrapper(iStream))
                            {
                                streamData(stream, fileDescriptor);
                            }
                        }
                        // Return an IntPtr for the IStream
                        ptr = Marshal.GetComInterfaceForObject(iStream, typeof(IStream));
                        Marshal.ReleaseComObject(iStream);
                        return new Tuple<IntPtr, int>(ptr, NativeMethods.S_OK);
                    },
                });
        }

19 Source : StreamWrapper.cs
with MIT License
from Bassman2

protected override void Dispose(bool disposing)
        {
            if (this.stream != null)
            {
                Marshal.ReleaseComObject(this.stream);
                this.stream = null;
            }
            if (this.pLength != IntPtr.Zero)
            {
                Marshal.FreeHGlobal(this.pLength);
                this.pLength = IntPtr.Zero;
            }
        }

19 Source : MultiMediaNotifications.cs
with MIT License
from BleuBleu

private void Dispose(bool disposing)
        {
            _deviceEnumerator.UnregisterEndpointNotificationCallback(this);
            Marshal.ReleaseComObject(_deviceEnumerator);
        }

19 Source : WinXHasher.cs
with MIT License
from BluePointLilac

public static void HashLnk(string lnkPath)
        {
            SHCreateItemFromParsingName(lnkPath, null, typeof(IShellItem2).GUID, out IShellItem item);
            IShellItem2 item2 = (IShellItem2)item;
            PSGetPropertyKeyFromName("System.Link.TargetParsingPath", out PropertyKey pk);
            //shellPKey = PKEY_Link_TargetParsingPath
            //formatID = B9B4B3FC-2B51-4A42-B5D8-324146AFCF25, propID = 2
            string targetPath;
            try { targetPath = item2.GetString(pk); }
            catch { targetPath = null; }

            PSGetPropertyKeyFromName("System.Link.Arguments", out pk);
            //shellPKey = PKEY_Link_Arguments
            //formatID = 436F2667-14E2-4FEB-B30A-146C53B5B674, propID = 100
            string arguments;
            try { arguments = item2.GetString(pk); }
            catch { arguments = null; }

            string blob = GetGeneralizePath(targetPath) + arguments;
            blob += "do not prehash links.  this should only be done by the user.";//特殊但必须存在的字符串
            blob = blob.ToLower();
            byte[] inBytes = Encoding.Unicode.GetBytes(blob);
            int byteCount = inBytes.Length;
            byte[] outBytes = new byte[byteCount];
            HashData(inBytes, byteCount, outBytes, byteCount);
            uint hash = BitConverter.ToUInt32(outBytes, 0);

            Guid guid = typeof(IPropertyStore).GUID;
            IPropertyStore store = item2.GetPropertyStore(GPS.READWRITE, ref guid);
            PSGetPropertyKeyFromName("System.Winx.Hash", out pk);
            //shellPKey = PKEY_WINX_HASH
            //formatID = FB8D2D7B-90D1-4E34-BF60-6EAC09922BBF, propID = 2
            PropVariant pv = new PropVariant { VarType = VarEnum.VT_UI4, ulVal = hash };
            store.SetValue(ref pk, ref pv);
            store.Commit();

            Marshal.ReleaseComObject(store);
            Marshal.ReleaseComObject(item);
        }

19 Source : DsDevice.cs
with MIT License
from BoonyaCSharp-ASP

public static bool GetDevicesOfCat(Guid cat, out ArrayList devs,out string _dsshow)
        {
            devs = null;
            _dsshow = "";
            int hr;
            object comObj = null;
            ICreateDevEnum enumDev = null;
            UCOMIEnumMoniker enumMon = null;
            UCOMIMoniker[] mon = new UCOMIMoniker[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.CreateClreplacedEnumerator(ref cat, out enumMon, 0);
                if (hr != 0)
                    throw new NotSupportedException("No devices of the category");

                int f, count = 0;
                do
                {
                    hr = enumMon.Next(1, mon, out f);
                    if ((hr != 0) || (mon[0] == null))
                        break;
                    DsDevice dev = new DsDevice();
                    dev.Name = GetFriendlyName(mon[0]);
                    if (devs == null)
                        devs = new ArrayList();
                    _dsshow = dev.Name;
                    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;
                    _dsshow = "";
                }
                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;
            }

        }

19 Source : DsDevice.cs
with MIT License
from BoonyaCSharp-ASP

private static string GetFriendlyName(UCOMIMoniker mon)
        {
            object bagObj = null;
            IPropertyBag bag = null;
            try
            {
                Guid bagId = typeof(IPropertyBag).GUID;
                mon.BindToStorage(null, null, ref bagId, out bagObj);
                bag = (IPropertyBag)bagObj;
                object val = "";
                int hr = bag.Read("FriendlyName", ref val, IntPtr.Zero);
                if (hr != 0)
                    Marshal.ThrowExceptionForHR(hr);
                string ret = val as string;
                if ((ret == null) || (ret.Length < 1))
                    throw new NotImplementedException("Device FriendlyName");
                return ret;
            }
            catch (Exception)
            {
                return null;
            }
            finally
            {
                bag = null;
                if (bagObj != null)
                    Marshal.ReleaseComObject(bagObj); bagObj = null;
            }
        }

19 Source : DsDevice.cs
with MIT License
from BoonyaCSharp-ASP

public void Dispose()
        {
            if (Mon != null)
                Marshal.ReleaseComObject(Mon); Mon = null;
        }

19 Source : DsDevice.cs
with MIT License
from BoonyaCSharp-ASP

public static string GetFriendlyName(UCOMIMoniker mon)
        {
            object bagObj = null;
            IPropertyBag bag = null;
            try
            {
                Guid bagId = typeof(IPropertyBag).GUID;
                mon.BindToStorage(null, null, ref bagId, out bagObj);
                bag = (IPropertyBag)bagObj;
                object val = "";
                int hr = bag.Read("FriendlyName", ref val, IntPtr.Zero);
                if (hr != 0)
                    Marshal.ThrowExceptionForHR(hr);
                string ret = val as string;
                if ((ret == null) || (ret.Length < 1))
                    throw new NotImplementedException("Device FriendlyName");
                return ret;
            }
            catch (Exception)
            {
                return null;
            }
            finally
            {
                bag = null;
                if (bagObj != null)
                    Marshal.ReleaseComObject(bagObj); bagObj = null;
            }
        }

19 Source : DsDevice.cs
with MIT License
from BoonyaCSharp-ASP

public static bool GetDevicesOfCat(Guid cat, out ArrayList devs)
        {
            devs = null;
            int hr;
            object comObj = null;
            ICreateDevEnum enumDev = null;
            UCOMIEnumMoniker enumMon = null;
            UCOMIMoniker[] mon = new UCOMIMoniker[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.CreateClreplacedEnumerator(ref cat, out enumMon, 0);
                if (hr != 0)
                    throw new NotSupportedException("No devices of the category");

                int f, count = 0;
                do
                {
                    hr = enumMon.Next(1, mon, out 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)
            {
                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;
            }

        }

19 Source : AudioDevices.cs
with GNU General Public License v3.0
from BRH-Media

internal bool PeakMeter_Open(AudioDevice device, bool change)
        {
            if (!pm_HasPeakMeter || change)
            {
                IMMDeviceEnumerator deviceEnumerator    = null;
                IMMDevice           levelDevice         = null;

                if (pm_HasPeakMeter) PeakMeter_Close();

                try
                {
                    deviceEnumerator = (IMMDeviceEnumerator)new MMDeviceEnumerator();
                    if (device == null) deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia, out levelDevice);
                    else deviceEnumerator.GetDevice(device._id, out levelDevice);

                    if (levelDevice != null)
                    {
                        levelDevice.Activate(ref IID_IAudioMeterInformation, 3, IntPtr.Zero, out object levelDeviceInfo);
                        pm_PeakMeterInfo = (IAudioMeterInformation)levelDeviceInfo;

                        pm_PeakMeterInfo.GetMeteringChannelCount(out pm_PeakMeterChannelCount);
                        if (pm_PeakMeterChannelCount > MAX_AUDIO_CHANNELS) pm_PeakMeterChannelCount = MAX_AUDIO_CHANNELS;

                        if (pm_PeakMeterValues == null)
                        {
                            pm_PeakMeterValues      = new float[MAX_AUDIO_CHANNELS];
                            pm_PeakMeterValuesStop  = new float[MAX_AUDIO_CHANNELS];
                            for (int i = 0; i < MAX_AUDIO_CHANNELS; i++)
                            {
                                pm_PeakMeterValuesStop[i] = STOP_VALUE;
                            }
                        }
                        pm_HasPeakMeter = true;

                        StartSystemDevicesChangedHandlerCheck();
                    }
                }
                catch { /* ignored */
    }

                if (levelDevice != null)        Marshal.ReleaseComObject(levelDevice);
                if (deviceEnumerator != null)   Marshal.ReleaseComObject(deviceEnumerator);
            }
            return pm_HasPeakMeter;
        }

19 Source : AudioDevices.cs
with GNU General Public License v3.0
from BRH-Media

internal void PeakMeter_Close()
        {
            if (pm_HasPeakMeter)
            {
                if (_playing && _mediaPeakLevelChanged != null)
                {
                    _outputLevelArgs._channelCount    = pm_PeakMeterChannelCount;
                    _outputLevelArgs._masterPeakValue = STOP_VALUE;
                    _outputLevelArgs._channelsValues  = pm_PeakMeterValuesStop;
                    _mediaPeakLevelChanged(this, _outputLevelArgs);
                }

                pm_PeakMeterChannelCount = 0;
                pm_PeakMeterMasterValue  = 0;
                pm_HasPeakMeter          = false;

                try
                {
                    Marshal.ReleaseComObject(pm_PeakMeterInfo);
                    pm_PeakMeterInfo = null;

                    StopSystemDevicesChangedHandlerCheck();
                }
                catch { /* ignored */ }
            }
        }

19 Source : AudioDevices.cs
with GNU General Public License v3.0
from BRH-Media

internal void InputMeter_Close()
        {
            if (pm_HasInputMeter)
            {
                if (_playing && _mediaPeakLevelChanged != null)
                {
                    _inputLevelArgs._channelCount = pm_InputMeterChannelCount;
                    _inputLevelArgs._masterPeakValue = STOP_VALUE;
                    _inputLevelArgs._channelsValues = pm_InputMeterValuesStop;
                    _mediaInputLevelChanged(this, _inputLevelArgs);
                }

                pm_InputMeterChannelCount = 0;
                pm_InputMeterMasterValue = 0;
                pm_HasInputMeter = false;

                try
                {
                    Marshal.ReleaseComObject(pm_InputMeterInfo);
                    pm_InputMeterInfo = null;

                    //StopSystemDevicesChangedHandlerCheck();
                }
                catch { /* ignored */ }
            }
        }

19 Source : AudioDevices.cs
with GNU General Public License v3.0
from BRH-Media

private void SystemDevicesChangedHandler(object sender, SystemAudioDevicesEventArgs e)
        {
            if (e.IsInputDevice) return;

            IMMDeviceEnumerator deviceEnumerator = (IMMDeviceEnumerator)new MMDeviceEnumerator();
            deviceEnumerator.EnumAudioEndpoints(EDataFlow.eRender, (uint)DeviceState.Active, out IMMDeviceCollection deviceCollection);
            deviceCollection.GetCount(out uint count);
            Marshal.ReleaseComObject(deviceEnumerator);
            if (deviceCollection != null) Marshal.ReleaseComObject(deviceCollection);

            if (e._notification == SystemAudioDevicesNotification.Activated)
            {
                if (count == 1)
                {
                    if (_playing && !_paused)
                    {
                        // cannot resume playback
                        //if (pm_HasPeakMeter)
                        //{
                        //    PeakMeter_Open(_audioDevice, true);
                        //}
                        // maybe this
                        Control control = _display;
                        if (control == null)
                        {
                            FormCollection forms = Application.OpenForms;
                            if (forms != null && forms.Count > 0) control = forms[0];
                        }
                        if (control != null)
                        {
                            control.BeginInvoke(new MethodInvoker(delegate { AV_UpdateTopology(); }));
                        }
                    }
                    _mediaAudioDeviceChanged?.Invoke(this, EventArgs.Empty);
                }
            }
            else if (_audioDevice == null)
            {
                if (pm_HasPeakMeter && e._notification == SystemAudioDevicesNotification.DefaultChanged)
                {
                    if (count != 0)
                    {
                        PeakMeter_Open(_audioDevice, true);
                    }
                    else pm_PeakMeterChannelCount = 0;
                    _mediaAudioDeviceChanged?.Invoke(this, EventArgs.Empty);
                }
            }
            else
            {
                if (e._deviceId == _audioDevice.Id && (e._notification == SystemAudioDevicesNotification.Removed || e._notification == SystemAudioDevicesNotification.Disabled))
                {
                    if (count != 0)
                    {
                        _audioDevice = null;
                        if (pm_HasPeakMeter) PeakMeter_Open(_audioDevice, true);
                    }
                    else pm_PeakMeterChannelCount = 0;
                    _mediaAudioDeviceChanged?.Invoke(this, EventArgs.Empty);
                }
            }
        }

19 Source : AudioDevices.cs
with GNU General Public License v3.0
from BRH-Media

internal static void AudioDevicesClientClose()
        {
            if (pm_AudioDevicesCallback != null)
            {
                try
                {
                    IMMDeviceEnumerator deviceEnumerator = (IMMDeviceEnumerator)(new MMDeviceEnumerator());
                    deviceEnumerator.UnregisterEndpointNotificationCallback(pm_AudioDevicesCallback);
                    pm_AudioDevicesCallback = null;
                    pm_AudioDevicesEventArgs = null;
                    if (deviceEnumerator != null) { Marshal.ReleaseComObject(deviceEnumerator); deviceEnumerator = null; }
                }
                catch { /* ignored */ }
            }
        }

19 Source : AudioDevices.cs
with GNU General Public License v3.0
from BRH-Media

private static bool IsAudioInputDevice(string deviceId)
        {
            bool result = false;

            IMMDeviceEnumerator deviceEnumerator = (IMMDeviceEnumerator)new MMDeviceEnumerator();
            deviceEnumerator.EnumAudioEndpoints(EDataFlow.eCapture, (uint)DeviceState.All, out IMMDeviceCollection deviceCollection);
            deviceCollection.GetCount(out uint count);
            Marshal.ReleaseComObject(deviceEnumerator);

            for (uint i = 0; i < count; i++)
            {
                deviceCollection.Item(i, out IMMDevice device);
                device.GetId(out string id);
                Marshal.ReleaseComObject(device);
                if (deviceId == id)
                {
                    result = true;
                    break;
                }
            }
            if (deviceCollection != null) Marshal.ReleaseComObject(deviceCollection);
            return result;
        }

See More Examples