internal static MemoryStream GetFileContents(System.Windows.IDataObject dataObject, int index) { //cast the default IDataObject to a com IDataObject IDataObject comDataObject; comDataObject = (IDataObject)dataObject; System.Windows.DataFormat Format = System.Windows.DataFormats.GetDataFormat("FileContents"); if (Format == null) { return(null); } FORMATETC formatetc = new FORMATETC(); formatetc.cfFormat = (short)Format.Id; formatetc.dwAspect = DVASPECT.DVASPECT_CONTENT; formatetc.lindex = index; formatetc.tymed = TYMED.TYMED_ISTREAM | TYMED.TYMED_HGLOBAL; //create STGMEDIUM to output request results into STGMEDIUM medium = new STGMEDIUM(); //using the com IDataObject interface get the data using the defined FORMATETC comDataObject.GetData(ref formatetc, out medium); switch (medium.tymed) { case TYMED.TYMED_ISTREAM: return(GetIStream(medium)); default: throw new NotSupportedException(); } }
/// <summary> /// Sets managed data to a clipboard DataObject. /// </summary> /// <param name="dataObject">The DataObject to set the data on.</param> /// <param name="format">The clipboard format.</param> /// <param name="data">The data object.</param> /// <remarks> /// Because the underlying data store is not storing managed objects, but /// unmanaged ones, this function provides intelligent conversion, allowing /// you to set unmanaged data into the COM implemented IDataObject.</remarks> public void SetDataEx(string format, object data) { System.Windows.DataFormat dataFormat = System.Windows.DataFormats.GetDataFormat(format); // Initialize the format structure FORMATETC formatETC = new FORMATETC { cfFormat = (short)dataFormat.Id, dwAspect = DVASPECT.DVASPECT_CONTENT, lindex = -1, ptd = IntPtr.Zero }; // Try to discover the TYMED from the format and data TYMED tymed = GetCompatibleTymed(format, data); // If a TYMED was found, we can use the system DataObject // to convert our value for us. if (tymed != TYMED.TYMED_NULL) { formatETC.tymed = tymed; // Set data on an empty DataObject instance System.Windows.DataObject conv = new System.Windows.DataObject(); conv.SetData(format, data, true); // Now retrieve the data, using the COM interface. // This will perform a managed to unmanaged conversion for us. ((IDataObject)conv).GetData(ref formatETC, out STGMEDIUM medium); try { // Now set the data on our data object SetData(ref formatETC, ref medium, true); } catch { // On exceptions, release the medium ReleaseStgMedium(ref medium); throw; } } else { // Since we couldn't determine a TYMED, this data // is likely custom managed data, and won't be used // by unmanaged code, so we'll use our custom marshaling // implemented by our COM IDataObject extensions. SetManagedData(format, data); } }