/// <summary> /// Writes an object to a specific clipboard format. /// </summary> /// <typeparam name="T">Type of object to store on the clipboard.</typeparam> /// <param name="cfFormat">The Id of the format to write.</param> /// <param name="obj">The object to write to the clipboard.</param> /// <param name="converter">The coverter responsible for writing the object to an HGlobal.</param> /// <exception cref="Exception">If the object was not written successfully.</exception> protected virtual void SetFormatObject <T>(uint cfFormat, T obj, IDataConverter <T> converter) { ThrowIfDisposed(); // EmptyClipboard must be called to update the current clipboard owner before setting data if (!_cleared) { Empty(); } var hglobal = converter.WriteToHGlobal(obj); if (hglobal == IntPtr.Zero) { throw new Exception("Unable to copy data into global memory"); } try { var hdata = NativeMethods.SetClipboardData(cfFormat, hglobal); if (hdata == IntPtr.Zero) { throw new Win32Exception(); } } catch { // free hglobal only if error, if success - ownership of hglobal has transferred to system NativeMethods.GlobalFree(hglobal); } }