/// <summary> /// Unregisters a form for receiving a callback notification when another instance was started. /// </summary> /// <param name="form">The form to register.</param> /// <exception cref="ArgumentNullException">Thrown when the specified form is null.</exception> /// <exception cref="ArgumentException">Thrown when the form is not registered.</exception> public void UnregisterForm(Form form) { if (form == null) { throw new ArgumentNullException(nameof(form)); } if (!_forms.Contains(form)) { return; } // If the form being unregistered is our listener form, release the filter. if (_messageFilter.Handle == form.Handle) { _messageFilter.ReleaseHandle(); } form.Disposed -= Form_Disposed; _forms.Remove(form); // If the filter was just released, reassign it to another form. if (_messageFilter.Handle != IntPtr.Zero || _forms.Count <= 0) { return; } foreach (var other in _forms) { Win32Exception lastEx; try { _messageFilter.AssignHandle(other.Handle); break; } catch (Win32Exception ex) { lastEx = ex; } if (_messageFilter.Handle == IntPtr.Zero) { throw new InvalidOperationException("An unexpected error occurred while attempting assign message filter.", lastEx); } } }
/// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> /// <param name="disposing">True if disposing.</param> private void Dispose(bool disposing) { if (_disposed) { return; } if (disposing) { _messageFilter?.ReleaseHandle(); _messageFilter = null; } if (_mutexOwned) { _mutex.ReleaseMutex(); } _mutex.Dispose(); _disposed = true; }