using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; using System.Windows; namespace Tango.FileSystem { /// /// Class implementing drag/drop and clipboard support for virtual files. /// Also offers an alternate interface to the IDataObject interface. /// public sealed class VirtualFileDataObject : System.Runtime.InteropServices.ComTypes.IDataObject, IAsyncOperation { /// /// Gets or sets a value indicating whether the data object can be used asynchronously. /// public bool IsAsynchronous { get; set; } /// /// Identifier for CFSTR_FILECONTENTS. /// private static short FILECONTENTS = (short)(DataFormats.GetDataFormat(NativeMethods.CFSTR_FILECONTENTS).Id); /// /// Identifier for CFSTR_FILEDESCRIPTORW. /// private static short FILEDESCRIPTORW = (short)(DataFormats.GetDataFormat(NativeMethods.CFSTR_FILEDESCRIPTORW).Id); /// /// Identifier for CFSTR_PASTESUCCEEDED. /// private static short PASTESUCCEEDED = (short)(DataFormats.GetDataFormat(NativeMethods.CFSTR_PASTESUCCEEDED).Id); /// /// Identifier for CFSTR_PERFORMEDDROPEFFECT. /// private static short PERFORMEDDROPEFFECT = (short)(DataFormats.GetDataFormat(NativeMethods.CFSTR_PERFORMEDDROPEFFECT).Id); /// /// Identifier for CFSTR_PREFERREDDROPEFFECT. /// private static short PREFERREDDROPEFFECT = (short)(DataFormats.GetDataFormat(NativeMethods.CFSTR_PREFERREDDROPEFFECT).Id); /// /// In-order list of registered data objects. /// private List _dataObjects = new List(); /// /// Tracks whether an asynchronous operation is ongoing. /// private bool _inOperation; /// /// Stores the user-specified start action. /// private Action _startAction; /// /// Stores the user-specified end action. /// private Action _endAction; /// /// Initializes a new instance of the VirtualFileDataObject class. /// public VirtualFileDataObject() { IsAsynchronous = true; } /// /// Initializes a new instance of the VirtualFileDataObject class. /// /// Optional action to run at the start of the data transfer. /// Optional action to run at the end of the data transfer. public VirtualFileDataObject(Action startAction, Action endAction) : this() { _startAction = startAction; _endAction = endAction; } #region IDataObject Members // Explicit interface implementation hides the technical details from users of VirtualFileDataObject. /// /// Creates a connection between a data object and an advisory sink. /// /// A FORMATETC structure that defines the format, target device, aspect, and medium that will be used for future notifications. /// One of the ADVF values that specifies a group of flags for controlling the advisory connection. /// A pointer to the IAdviseSink interface on the advisory sink that will receive the change notification. /// When this method returns, contains a pointer to a DWORD token that identifies this connection. /// HRESULT success code. [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Method doesn't decrease security.")] int System.Runtime.InteropServices.ComTypes.IDataObject.DAdvise(ref FORMATETC pFormatetc, ADVF advf, IAdviseSink adviseSink, out int connection) { Marshal.ThrowExceptionForHR(NativeMethods.OLE_E_ADVISENOTSUPPORTED); throw new NotImplementedException(); } /// /// Destroys a notification connection that had been previously established. /// /// A DWORD token that specifies the connection to remove. [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Method doesn't decrease security.")] void System.Runtime.InteropServices.ComTypes.IDataObject.DUnadvise(int connection) { Marshal.ThrowExceptionForHR(NativeMethods.OLE_E_ADVISENOTSUPPORTED); throw new NotImplementedException(); } /// /// Creates an object that can be used to enumerate the current advisory connections. /// /// When this method returns, contains an IEnumSTATDATA that receives the interface pointer to the new enumerator object. /// HRESULT success code. [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Method doesn't decrease security.")] int System.Runtime.InteropServices.ComTypes.IDataObject.EnumDAdvise(out IEnumSTATDATA enumAdvise) { Marshal.ThrowExceptionForHR(NativeMethods.OLE_E_ADVISENOTSUPPORTED); throw new NotImplementedException(); } /// /// Creates an object for enumerating the FORMATETC structures for a data object. /// /// One of the DATADIR values that specifies the direction of the data. /// IEnumFORMATETC interface. [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Method doesn't decrease security.")] IEnumFORMATETC System.Runtime.InteropServices.ComTypes.IDataObject.EnumFormatEtc(DATADIR direction) { if (direction == DATADIR.DATADIR_GET) { if (0 == _dataObjects.Count) { // Note: SHCreateStdEnumFmtEtc fails for a count of 0; throw helpful exception throw new InvalidOperationException("VirtualFileDataObject requires at least one data object to enumerate."); } // Create enumerator and return it IEnumFORMATETC enumerator; if (NativeMethods.SUCCEEDED(NativeMethods.SHCreateStdEnumFmtEtc((uint)(_dataObjects.Count), _dataObjects.Select(d => d.FORMATETC).ToArray(), out enumerator))) { return enumerator; } // Returning null here can cause an AV in the caller; throw instead Marshal.ThrowExceptionForHR(NativeMethods.E_FAIL); } throw new NotImplementedException(); } /// /// Provides a standard FORMATETC structure that is logically equivalent to a more complex structure. /// /// A pointer to a FORMATETC structure that defines the format, medium, and target device that the caller would like to use to retrieve data in a subsequent call such as GetData. /// When this method returns, contains a pointer to a FORMATETC structure that contains the most general information possible for a specific rendering, making it canonically equivalent to formatetIn. /// HRESULT success code. int System.Runtime.InteropServices.ComTypes.IDataObject.GetCanonicalFormatEtc(ref FORMATETC formatIn, out FORMATETC formatOut) { throw new NotImplementedException(); } /// /// Obtains data from a source data object. /// /// A pointer to a FORMATETC structure that defines the format, medium, and target device to use when passing the data. /// When this method returns, contains a pointer to the STGMEDIUM structure that indicates the storage medium containing the returned data through its tymed member, and the responsibility for releasing the medium through the value of its pUnkForRelease member. [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Method doesn't decrease security.")] void System.Runtime.InteropServices.ComTypes.IDataObject.GetData(ref FORMATETC format, out STGMEDIUM medium) { medium = new STGMEDIUM(); var hr = ((System.Runtime.InteropServices.ComTypes.IDataObject)this).QueryGetData(ref format); if (NativeMethods.SUCCEEDED(hr)) { // Find the best match var formatCopy = format; // Cannot use ref or out parameter inside an anonymous method, lambda expression, or query expression var dataObject = _dataObjects .Where(d => (d.FORMATETC.cfFormat == formatCopy.cfFormat) && (d.FORMATETC.dwAspect == formatCopy.dwAspect) && (0 != (d.FORMATETC.tymed & formatCopy.tymed) && (d.FORMATETC.lindex == formatCopy.lindex))) .FirstOrDefault(); if (dataObject != null) { if (!IsAsynchronous && (FILEDESCRIPTORW == dataObject.FORMATETC.cfFormat) && !_inOperation) { // Enter the operation and call the start action _inOperation = true; if (null != _startAction) { _startAction(this); } } // Populate the STGMEDIUM medium.tymed = dataObject.FORMATETC.tymed; var result = dataObject.GetData(); // Possible call to user code hr = result.Item2; if (NativeMethods.SUCCEEDED(hr)) { medium.unionmember = result.Item1; } } else { // Couldn't find a match hr = NativeMethods.DV_E_FORMATETC; } } if (!NativeMethods.SUCCEEDED(hr)) // Not redundant; hr gets updated in the block above { Marshal.ThrowExceptionForHR(hr); } } /// /// Obtains data from a source data object. /// /// A pointer to a FORMATETC structure that defines the format, medium, and target device to use when passing the data. /// A STGMEDIUM that defines the storage medium containing the data being transferred. void System.Runtime.InteropServices.ComTypes.IDataObject.GetDataHere(ref FORMATETC format, ref STGMEDIUM medium) { throw new NotImplementedException(); } /// /// Determines whether the data object is capable of rendering the data described in the FORMATETC structure. /// /// A pointer to a FORMATETC structure that defines the format, medium, and target device to use for the query. /// HRESULT success code. int System.Runtime.InteropServices.ComTypes.IDataObject.QueryGetData(ref FORMATETC format) { var formatCopy = format; // Cannot use ref or out parameter inside an anonymous method, lambda expression, or query expression var formatMatches = _dataObjects.Where(d => d.FORMATETC.cfFormat == formatCopy.cfFormat); if (!formatMatches.Any()) { return NativeMethods.DV_E_FORMATETC; } var tymedMatches = formatMatches.Where(d => 0 != (d.FORMATETC.tymed & formatCopy.tymed)); if (!tymedMatches.Any()) { return NativeMethods.DV_E_TYMED; } var aspectMatches = tymedMatches.Where(d => d.FORMATETC.dwAspect == formatCopy.dwAspect); if (!aspectMatches.Any()) { return NativeMethods.DV_E_DVASPECT; } return NativeMethods.S_OK; } /// /// Transfers data to the object that implements this method. /// /// A FORMATETC structure that defines the format used by the data object when interpreting the data contained in the storage medium. /// A STGMEDIUM structure that defines the storage medium in which the data is being passed. /// true to specify that the data object called, which implements SetData, owns the storage medium after the call returns. [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Method doesn't decrease security.")] void System.Runtime.InteropServices.ComTypes.IDataObject.SetData(ref FORMATETC formatIn, ref STGMEDIUM medium, bool release) { var handled = false; if ((formatIn.dwAspect == DVASPECT.DVASPECT_CONTENT) && (formatIn.tymed == TYMED.TYMED_HGLOBAL) && (medium.tymed == formatIn.tymed)) { // Supported format; capture the data var ptr = NativeMethods.GlobalLock(medium.unionmember); if (IntPtr.Zero != ptr) { try { var length = NativeMethods.GlobalSize(ptr).ToInt32(); var data = new byte[length]; Marshal.Copy(ptr, data, 0, length); // Store it in our own format SetData(formatIn.cfFormat, data); handled = true; } finally { NativeMethods.GlobalUnlock(medium.unionmember); } } // Release memory if we now own it if (release) { Marshal.FreeHGlobal(medium.unionmember); } } // Handle synchronous mode if (!IsAsynchronous && (PERFORMEDDROPEFFECT == formatIn.cfFormat) && _inOperation) { // Call the end action and exit the operation if (null != _endAction) { _endAction(this); } _inOperation = false; } // Throw if unhandled if (!handled) { throw new NotImplementedException(); } } #endregion /// /// Provides data for the specified data format (HGLOBAL). /// /// Data format. /// Sequence of data. public void SetData(short dataFormat, IEnumerable data) { _dataObjects.Add( new DataObject { FORMATETC = new FORMATETC { cfFormat = dataFormat, ptd = IntPtr.Zero, dwAspect = DVASPECT.DVASPECT_CONTENT, lindex = -1, tymed = TYMED.TYMED_HGLOBAL }, GetData = () => { var dataArray = data.ToArray(); var ptr = Marshal.AllocHGlobal(dataArray.Length); Marshal.Copy(dataArray, 0, ptr, dataArray.Length); return new Tuple(ptr, NativeMethods.S_OK); }, }); } /// /// Provides data for the specified data format and index (ISTREAM). /// /// Data format. /// Index of data. /// Action generating the data. /// /// Uses Stream instead of IEnumerable(T) because Stream is more likely /// to be natural for the expected scenarios. /// public void SetData(short dataFormat, int index, Action 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); } } // Return an IntPtr for the IStream ptr = Marshal.GetComInterfaceForObject(iStream, typeof(IStream)); Marshal.ReleaseComObject(iStream); return new Tuple(ptr, NativeMethods.S_OK); }, }); } /// /// Provides data for the specified data format (FILEGROUPDESCRIPTOR/FILEDESCRIPTOR) /// /// Collection of virtual files. public void SetData(IEnumerable fileDescriptors) { // Prepare buffer var bytes = new List(); // Add FILEGROUPDESCRIPTOR header bytes.AddRange(StructureBytes(new NativeMethods.FILEGROUPDESCRIPTOR { cItems = (uint)(fileDescriptors.Count()) })); // Add n FILEDESCRIPTORs foreach (var fileDescriptor in fileDescriptors) { // Set required fields var FILEDESCRIPTOR = new NativeMethods.FILEDESCRIPTOR { cFileName = fileDescriptor.Name, }; // Set optional timestamp if (fileDescriptor.ChangeTimeUtc.HasValue) { FILEDESCRIPTOR.dwFlags |= NativeMethods.FD_CREATETIME | NativeMethods.FD_WRITESTIME; var changeTime = fileDescriptor.ChangeTimeUtc.Value.ToLocalTime().ToFileTime(); var changeTimeFileTime = new System.Runtime.InteropServices.ComTypes.FILETIME { dwLowDateTime = (int)(changeTime & 0xffffffff), dwHighDateTime = (int)(changeTime >> 32), }; FILEDESCRIPTOR.ftLastWriteTime = changeTimeFileTime; FILEDESCRIPTOR.ftCreationTime = changeTimeFileTime; } // Set optional length if (fileDescriptor.Length.HasValue) { FILEDESCRIPTOR.dwFlags |= NativeMethods.FD_FILESIZE; FILEDESCRIPTOR.nFileSizeLow = (uint)(fileDescriptor.Length & 0xffffffff); FILEDESCRIPTOR.nFileSizeHigh = (uint)(fileDescriptor.Length >> 32); } // Add structure to buffer bytes.AddRange(StructureBytes(FILEDESCRIPTOR)); } // Set CFSTR_FILEDESCRIPTORW SetData(FILEDESCRIPTORW, bytes); // Set n CFSTR_FILECONTENTS var index = 0; foreach (var fileDescriptor in fileDescriptors) { SetData(FILECONTENTS, index, fileDescriptor.StreamContents); index++; } } /// /// Gets or sets the CFSTR_PASTESUCCEEDED value for the object. /// public DragDropEffects? PasteSucceeded { get { return GetDropEffect(PASTESUCCEEDED); } set { SetData(PASTESUCCEEDED, BitConverter.GetBytes((UInt32)value)); } } /// /// Gets or sets the CFSTR_PERFORMEDDROPEFFECT value for the object. /// public DragDropEffects? PerformedDropEffect { get { return GetDropEffect(PERFORMEDDROPEFFECT); } set { SetData(PERFORMEDDROPEFFECT, BitConverter.GetBytes((UInt32)value)); } } /// /// Gets or sets the CFSTR_PREFERREDDROPEFFECT value for the object. /// public DragDropEffects? PreferredDropEffect { get { return GetDropEffect(PREFERREDDROPEFFECT); } set { SetData(PREFERREDDROPEFFECT, BitConverter.GetBytes((UInt32)value)); } } /// /// Gets the DragDropEffects value (if any) previously set on the object. /// /// Clipboard format. /// DragDropEffects value or null. [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Method doesn't decrease security.")] private DragDropEffects? GetDropEffect(short format) { // Get the most recent setting var dataObject = _dataObjects .Where(d => (format == d.FORMATETC.cfFormat) && (DVASPECT.DVASPECT_CONTENT == d.FORMATETC.dwAspect) && (TYMED.TYMED_HGLOBAL == d.FORMATETC.tymed)) .LastOrDefault(); if (null != dataObject) { // Read the value and return it var result = dataObject.GetData(); if (NativeMethods.SUCCEEDED(result.Item2)) { var ptr = NativeMethods.GlobalLock(result.Item1); if (IntPtr.Zero != ptr) { try { var length = NativeMethods.GlobalSize(ptr).ToInt32(); if (4 == length) { var data = new byte[length]; Marshal.Copy(ptr, data, 0, length); return (DragDropEffects)(BitConverter.ToUInt32(data, 0)); } } finally { NativeMethods.GlobalUnlock(result.Item1); } } } } return null; } #region IAsyncOperation Members // Explicit interface implementation hides the technical details from users of VirtualFileDataObject. /// /// Called by a drop source to specify whether the data object supports asynchronous data extraction. /// /// A Boolean value that is set to VARIANT_TRUE to indicate that an asynchronous operation is supported, or VARIANT_FALSE otherwise. void IAsyncOperation.SetAsyncMode(int fDoOpAsync) { IsAsynchronous = !(NativeMethods.VARIANT_FALSE == fDoOpAsync); } /// /// Called by a drop target to determine whether the data object supports asynchronous data extraction. /// /// A Boolean value that is set to VARIANT_TRUE to indicate that an asynchronous operation is supported, or VARIANT_FALSE otherwise. void IAsyncOperation.GetAsyncMode(out int pfIsOpAsync) { pfIsOpAsync = IsAsynchronous ? NativeMethods.VARIANT_TRUE : NativeMethods.VARIANT_FALSE; } /// /// Called by a drop target to indicate that asynchronous data extraction is starting. /// /// Reserved. Set this value to NULL. void IAsyncOperation.StartOperation(IBindCtx pbcReserved) { _inOperation = true; if (null != _startAction) { _startAction(this); } } /// /// Called by the drop source to determine whether the target is extracting data asynchronously. /// /// Set to VARIANT_TRUE if data extraction is being handled asynchronously, or VARIANT_FALSE otherwise. void IAsyncOperation.InOperation(out int pfInAsyncOp) { pfInAsyncOp = _inOperation ? NativeMethods.VARIANT_TRUE : NativeMethods.VARIANT_FALSE; } /// /// Notifies the data object that that asynchronous data extraction has ended. /// /// An HRESULT value that indicates the outcome of the data extraction. Set to S_OK if successful, or a COM error code otherwise. /// Reserved. Set to NULL. /// A DROPEFFECT value that indicates the result of an optimized move. This should be the same value that would be passed to the data object as a CFSTR_PERFORMEDDROPEFFECT format with a normal data extraction operation. void IAsyncOperation.EndOperation(int hResult, IBindCtx pbcReserved, uint dwEffects) { if (null != _endAction) { _endAction(this); } _inOperation = false; } #endregion /// /// Returns the in-memory representation of an interop structure. /// /// Structure to return. /// In-memory representation of structure. [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Method doesn't decrease security.")] private static IEnumerable StructureBytes(object source) { // Set up for call to StructureToPtr var size = Marshal.SizeOf(source.GetType()); var ptr = Marshal.AllocHGlobal(size); var bytes = new byte[size]; try { Marshal.StructureToPtr(source, ptr, false); // Copy marshalled bytes to buffer Marshal.Copy(ptr, bytes, 0, size); } finally { Marshal.FreeHGlobal(ptr); } return bytes; } /// /// Class representing a virtual file for use by drag/drop or the clipboard. /// [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Justification = "Deliberate to provide obvious coupling.")] public class FileDescriptor { /// /// Gets or sets the name of the file. /// public string Name { get; set; } /// /// Gets or sets the (optional) length of the file. /// public Int64? Length { get; set; } /// /// Gets or sets the (optional) change time of the file. /// public DateTime? ChangeTimeUtc { get; set; } /// /// Gets or sets an Action that returns the contents of the file. /// public Action StreamContents { get; set; } } /// /// Class representing the result of a SetData call. /// private class DataObject { /// /// FORMATETC structure for the data. /// public FORMATETC FORMATETC { get; set; } /// /// Func returning the data as an IntPtr and an HRESULT success code. /// public Func> GetData { get; set; } } /// /// Represents a 2-tuple, or pair. /// /// /// Minimal implementation of the .NET 4 Tuple class; remove if running on .NET 4. /// /// The type of the tuple's first component. /// The type of the tuple's second component. private class Tuple { /// /// Gets the value of the current Tuple(T1, T2) object's first component. /// public T1 Item1 { get; private set; } /// /// Gets the value of the current Tuple(T1, T2) object's second component. /// public T2 Item2 { get; private set; } /// /// Initializes a new instance of the Tuple(T1, T2) class. /// /// The value of the tuple's first component. /// The value of the tuple's second component. public Tuple(T1 item1, T2 item2) { Item1 = item1; Item2 = item2; } } /// /// Simple class that exposes a write-only IStream as a Stream. /// private class IStreamWrapper : Stream { /// /// IStream instance being wrapped. /// private IStream _iStream; /// /// Initializes a new instance of the IStreamWrapper class. /// /// IStream instance to wrap. public IStreamWrapper(IStream iStream) { _iStream = iStream; } /// /// Gets a value indicating whether the current stream supports reading. /// public override bool CanRead { get { return false; } } /// /// Gets a value indicating whether the current stream supports seeking. /// public override bool CanSeek { get { return false; } } /// /// Gets a value indicating whether the current stream supports writing. /// public override bool CanWrite { get { return true; } } /// /// Clears all buffers for this stream and causes any buffered data to be written to the underlying device. /// public override void Flush() { throw new NotImplementedException(); } /// /// Gets the length in bytes of the stream. /// public override long Length { get { throw new NotImplementedException(); } } /// /// Gets or sets the position within the current stream. /// public override long Position { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } /// /// Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read. /// /// An array of bytes. When this method returns, the buffer contains the specified byte array with the values between offset and (offset + count - 1) replaced by the bytes read from the current source. /// The zero-based byte offset in buffer at which to begin storing the data read from the current stream. /// The maximum number of bytes to be read from the current stream. /// The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached. public override int Read(byte[] buffer, int offset, int count) { throw new NotImplementedException(); } /// /// Sets the position within the current stream. /// /// A byte offset relative to the origin parameter. /// A value of type SeekOrigin indicating the reference point used to obtain the new position. /// The new position within the current stream. public override long Seek(long offset, SeekOrigin origin) { throw new NotImplementedException(); } /// /// Sets the length of the current stream. /// /// The desired length of the current stream in bytes. public override void SetLength(long value) { throw new NotImplementedException(); } /// /// Writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written. /// /// An array of bytes. This method copies count bytes from buffer to the current stream. /// The zero-based byte offset in buffer at which to begin copying bytes to the current stream. /// The number of bytes to be written to the current stream. public override void Write(byte[] buffer, int offset, int count) { if (offset == 0) { // Optimize common case to avoid creating extra buffers _iStream.Write(buffer, count, IntPtr.Zero); } else { // Easy way to provide the relevant byte[] _iStream.Write(buffer.Skip(offset).ToArray(), count, IntPtr.Zero); } } } /// /// Initiates a drag-and-drop operation. /// /// A reference to the dependency object that is the source of the data being dragged. /// A data object that contains the data being dragged. /// One of the DragDropEffects values that specifies permitted effects of the drag-and-drop operation. /// One of the DragDropEffects values that specifies the final effect that was performed during the drag-and-drop operation. /// /// Call this method instead of System.Windows.DragDrop.DoDragDrop because this method handles IDataObject better. /// [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "dragSource", Justification = "Parameter is present so the signature matches that of System.Windows.DragDrop.DoDragDrop.")] public static DragDropEffects DoDragDrop(DependencyObject dragSource, System.Runtime.InteropServices.ComTypes.IDataObject dataObject, DragDropEffects allowedEffects) { int[] finalEffect = new int[1]; try { NativeMethods.DoDragDrop(dataObject, new DropSource(), (int)allowedEffects, finalEffect); } finally { var virtualFileDataObject = dataObject as VirtualFileDataObject; if ((null != virtualFileDataObject) && !virtualFileDataObject.IsAsynchronous && virtualFileDataObject._inOperation) { // Call the end action and exit the operation if (null != virtualFileDataObject._endAction) { virtualFileDataObject._endAction(virtualFileDataObject); } virtualFileDataObject._inOperation = false; } } return (DragDropEffects)(finalEffect[0]); } /// /// Contains the methods for generating visual feedback to the end user and for canceling or completing the drag-and-drop operation. /// private class DropSource : NativeMethods.IDropSource { /// /// Determines whether a drag-and-drop operation should continue. /// /// Indicates whether the Esc key has been pressed since the previous call to QueryContinueDrag or to DoDragDrop if this is the first call to QueryContinueDrag. A TRUE value indicates the end user has pressed the escape key; a FALSE value indicates it has not been pressed. /// The current state of the keyboard modifier keys on the keyboard. Possible values can be a combination of any of the flags MK_CONTROL, MK_SHIFT, MK_ALT, MK_BUTTON, MK_LBUTTON, MK_MBUTTON, and MK_RBUTTON. /// This method returns S_OK/DRAGDROP_S_DROP/DRAGDROP_S_CANCEL on success. public int QueryContinueDrag(int fEscapePressed, uint grfKeyState) { var escapePressed = (0 != fEscapePressed); var keyStates = (DragDropKeyStates)grfKeyState; if (escapePressed) { return NativeMethods.DRAGDROP_S_CANCEL; } else if (DragDropKeyStates.None == (keyStates & DragDropKeyStates.LeftMouseButton)) { return NativeMethods.DRAGDROP_S_DROP; } return NativeMethods.S_OK; } /// /// Gives visual feedback to an end user during a drag-and-drop operation. /// /// The DROPEFFECT value returned by the most recent call to IDropTarget::DragEnter, IDropTarget::DragOver, or IDropTarget::DragLeave. /// This method returns S_OK on success. public int GiveFeedback(uint dwEffect) { return NativeMethods.DRAGDROP_S_USEDEFAULTCURSORS; } } /// /// Provides access to Win32-level constants, structures, and functions. /// private static class NativeMethods { public const int DRAGDROP_S_DROP = 0x00040100; public const int DRAGDROP_S_CANCEL = 0x00040101; public const int DRAGDROP_S_USEDEFAULTCURSORS = 0x00040102; public const int DV_E_DVASPECT = -2147221397; public const int DV_E_FORMATETC = -2147221404; public const int DV_E_TYMED = -2147221399; public const int E_FAIL = -2147467259; public const uint FD_CREATETIME = 0x00000008; public const uint FD_WRITESTIME = 0x00000020; public const uint FD_FILESIZE = 0x00000040; public const int OLE_E_ADVISENOTSUPPORTED = -2147221501; public const int S_OK = 0; public const int S_FALSE = 1; public const int VARIANT_FALSE = 0; public const int VARIANT_TRUE = -1; public const string CFSTR_FILECONTENTS = "FileContents"; public const string CFSTR_FILEDESCRIPTORW = "FileGroupDescriptorW"; public const string CFSTR_PASTESUCCEEDED = "Paste Succeeded"; public const string CFSTR_PERFORMEDDROPEFFECT = "Performed DropEffect"; public const string CFSTR_PREFERREDDROPEFFECT = "Preferred DropEffect"; [SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "Structure exists for interop.")] [StructLayout(LayoutKind.Sequential)] public struct FILEGROUPDESCRIPTOR { public UInt32 cItems; // Followed by 0 or more FILEDESCRIPTORs } [SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "Structure exists for interop.")] [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct FILEDESCRIPTOR { public UInt32 dwFlags; public Guid clsid; public Int32 sizelcx; public Int32 sizelcy; public Int32 pointlx; public Int32 pointly; public UInt32 dwFileAttributes; public System.Runtime.InteropServices.ComTypes.FILETIME ftCreationTime; public System.Runtime.InteropServices.ComTypes.FILETIME ftLastAccessTime; public System.Runtime.InteropServices.ComTypes.FILETIME ftLastWriteTime; public UInt32 nFileSizeHigh; public UInt32 nFileSizeLow; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] public string cFileName; } [ComImport] [Guid("00000121-0000-0000-C000-000000000046")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IDropSource { [PreserveSig] int QueryContinueDrag(int fEscapePressed, uint grfKeyState); [PreserveSig] int GiveFeedback(uint dwEffect); } [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "2#", Justification = "Win32 API.")] [DllImport("shell32.dll")] public static extern int SHCreateStdEnumFmtEtc(uint cfmt, FORMATETC[] afmt, out IEnumFORMATETC ppenumFormatEtc); [return: MarshalAs(UnmanagedType.Interface)] [DllImport("ole32.dll", PreserveSig = false)] public static extern IStream CreateStreamOnHGlobal(IntPtr hGlobal, [MarshalAs(UnmanagedType.Bool)] bool fDeleteOnRelease); [DllImport("ole32.dll", CharSet = CharSet.Auto, ExactSpelling = true, PreserveSig = false)] public static extern void DoDragDrop(System.Runtime.InteropServices.ComTypes.IDataObject dataObject, IDropSource dropSource, int allowedEffects, int[] finalEffect); [DllImport("kernel32.dll")] public static extern IntPtr GlobalLock(IntPtr hMem); [return: MarshalAs(UnmanagedType.Bool)] [DllImport("kernel32.dll")] public static extern bool GlobalUnlock(IntPtr hMem); [DllImport("kernel32.dll")] public static extern IntPtr GlobalSize(IntPtr handle); /// /// Returns true iff the HRESULT is a success code. /// /// HRESULT to check. /// True iff a success code. public static bool SUCCEEDED(int hr) { return (0 <= hr); } } } /// /// Definition of the IAsyncOperation COM interface. /// /// /// Pseudo-public because VirtualFileDataObject implements it. /// [ComImport] [Guid("3D8B0590-F691-11d2-8EA9-006097DF5BD4")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IAsyncOperation { void SetAsyncMode([In] Int32 fDoOpAsync); void GetAsyncMode([Out] out Int32 pfIsOpAsync); void StartOperation([In] IBindCtx pbcReserved); void InOperation([Out] out Int32 pfInAsyncOp); void EndOperation([In] Int32 hResult, [In] IBindCtx pbcReserved, [In] UInt32 dwEffects); } }