VirtualFileDataObject.cs 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics.CodeAnalysis;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Runtime.InteropServices;
  7. using System.Runtime.InteropServices.ComTypes;
  8. using System.Windows;
  9. namespace MarkdownRenderer.Test
  10. {
  11. /*************************************
  12. * https://dlaa.me/blog/post/9913083 *
  13. *************************************/
  14. /// <summary>
  15. /// Class implementing drag/drop and clipboard support for virtual files.
  16. /// Also offers an alternate interface to the IDataObject interface.
  17. /// </summary>
  18. internal sealed class VirtualFileDataObject : System.Runtime.InteropServices.ComTypes.IDataObject, IAsyncOperation
  19. {
  20. // ReSharper disable InconsistentNaming
  21. /// <summary>
  22. /// Gets or sets a value indicating whether the data object can be used asynchronously.
  23. /// </summary>
  24. public bool IsAsynchronous { get; set; }
  25. /// <summary>
  26. /// Identifier for CFSTR_FILECONTENTS.
  27. /// </summary>
  28. private static readonly short FILECONTENTS = (short)DataFormats.GetDataFormat(NativeMethods.CFSTR_FILECONTENTS).Id;
  29. /// <summary>
  30. /// Identifier for CFSTR_FILEDESCRIPTORW.
  31. /// </summary>
  32. private static readonly short FILEDESCRIPTORW = (short)DataFormats.GetDataFormat(NativeMethods.CFSTR_FILEDESCRIPTORW).Id;
  33. /// <summary>
  34. /// Identifier for CFSTR_PASTESUCCEEDED.
  35. /// </summary>
  36. private static readonly short PASTESUCCEEDED = (short)DataFormats.GetDataFormat(NativeMethods.CFSTR_PASTESUCCEEDED).Id;
  37. /// <summary>
  38. /// Identifier for CFSTR_PERFORMEDDROPEFFECT.
  39. /// </summary>
  40. private static readonly short PERFORMEDDROPEFFECT = (short)DataFormats.GetDataFormat(NativeMethods.CFSTR_PERFORMEDDROPEFFECT).Id;
  41. /// <summary>
  42. /// Identifier for CFSTR_PREFERREDDROPEFFECT.
  43. /// </summary>
  44. private static readonly short PREFERREDDROPEFFECT = (short)DataFormats.GetDataFormat(NativeMethods.CFSTR_PREFERREDDROPEFFECT).Id;
  45. // ReSharper restore InconsistentNaming
  46. /// <summary>
  47. /// In-order list of registered data objects.
  48. /// </summary>
  49. private readonly List<DataObject> _dataObjects = new List<DataObject>();
  50. /// <summary>
  51. /// Tracks whether an asynchronous operation is ongoing.
  52. /// </summary>
  53. private bool _inOperation;
  54. /// <summary>
  55. /// Stores the user-specified start action.
  56. /// </summary>
  57. private readonly Action<VirtualFileDataObject> _startAction;
  58. /// <summary>
  59. /// Stores the user-specified end action.
  60. /// </summary>
  61. private readonly Action<VirtualFileDataObject> _endAction;
  62. /// <summary>
  63. /// Initializes a new instance of the VirtualFileDataObject class.
  64. /// </summary>
  65. public VirtualFileDataObject()
  66. {
  67. IsAsynchronous = true;
  68. }
  69. /// <summary>
  70. /// Initializes a new instance of the VirtualFileDataObject class.
  71. /// </summary>
  72. /// <param name="startAction">Optional action to run at the start of the data transfer.</param>
  73. /// <param name="endAction">Optional action to run at the end of the data transfer.</param>
  74. public VirtualFileDataObject(Action<VirtualFileDataObject> startAction, Action<VirtualFileDataObject> endAction)
  75. : this()
  76. {
  77. _startAction = startAction;
  78. _endAction = endAction;
  79. }
  80. #region IDataObject Members
  81. // Explicit interface implementation hides the technical details from users of VirtualFileDataObject.
  82. /// <summary>
  83. /// Creates a connection between a data object and an advisory sink.
  84. /// </summary>
  85. /// <param name="pFormatetc">A FORMATETC structure that defines the format, target device, aspect, and medium that will be used for future notifications.</param>
  86. /// <param name="advf">One of the ADVF values that specifies a group of flags for controlling the advisory connection.</param>
  87. /// <param name="adviseSink">A pointer to the IAdviseSink interface on the advisory sink that will receive the change notification.</param>
  88. /// <param name="connection">When this method returns, contains a pointer to a DWORD token that identifies this connection.</param>
  89. /// <returns>HRESULT success code.</returns>
  90. [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Method doesn't decrease security.")]
  91. int System.Runtime.InteropServices.ComTypes.IDataObject.DAdvise(ref FORMATETC pFormatetc, ADVF advf, IAdviseSink adviseSink, out int connection)
  92. {
  93. Marshal.ThrowExceptionForHR(NativeMethods.OLE_E_ADVISENOTSUPPORTED);
  94. throw new NotImplementedException();
  95. }
  96. /// <summary>
  97. /// Destroys a notification connection that had been previously established.
  98. /// </summary>
  99. /// <param name="connection">A DWORD token that specifies the connection to remove.</param>
  100. [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Method doesn't decrease security.")]
  101. void System.Runtime.InteropServices.ComTypes.IDataObject.DUnadvise(int connection)
  102. {
  103. Marshal.ThrowExceptionForHR(NativeMethods.OLE_E_ADVISENOTSUPPORTED);
  104. throw new NotImplementedException();
  105. }
  106. /// <summary>
  107. /// Creates an object that can be used to enumerate the current advisory connections.
  108. /// </summary>
  109. /// <param name="enumAdvise">When this method returns, contains an IEnumSTATDATA that receives the interface pointer to the new enumerator object.</param>
  110. /// <returns>HRESULT success code.</returns>
  111. [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Method doesn't decrease security.")]
  112. int System.Runtime.InteropServices.ComTypes.IDataObject.EnumDAdvise(out IEnumSTATDATA enumAdvise)
  113. {
  114. Marshal.ThrowExceptionForHR(NativeMethods.OLE_E_ADVISENOTSUPPORTED);
  115. throw new NotImplementedException();
  116. }
  117. /// <summary>
  118. /// Creates an object for enumerating the FORMATETC structures for a data object.
  119. /// </summary>
  120. /// <param name="direction">One of the DATADIR values that specifies the direction of the data.</param>
  121. /// <returns>IEnumFORMATETC interface.</returns>
  122. [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Method doesn't decrease security.")]
  123. IEnumFORMATETC System.Runtime.InteropServices.ComTypes.IDataObject.EnumFormatEtc(DATADIR direction)
  124. {
  125. if (direction == DATADIR.DATADIR_GET)
  126. {
  127. if (0 == _dataObjects.Count)
  128. {
  129. // Note: SHCreateStdEnumFmtEtc fails for a count of 0; throw helpful exception
  130. throw new InvalidOperationException("VirtualFileDataObject requires at least one data object to enumerate.");
  131. }
  132. // Create enumerator and return it
  133. IEnumFORMATETC enumerator;
  134. if (NativeMethods.IsSucceededHresult(NativeMethods.SHCreateStdEnumFmtEtc((uint)_dataObjects.Count, _dataObjects.Select(d => d.Formatetc).ToArray(), out enumerator)))
  135. {
  136. return enumerator;
  137. }
  138. // Returning null here can cause an AV in the caller; throw instead
  139. Marshal.ThrowExceptionForHR(NativeMethods.E_FAIL);
  140. }
  141. throw new NotImplementedException();
  142. }
  143. /// <summary>
  144. /// Provides a standard FORMATETC structure that is logically equivalent to a more complex structure.
  145. /// </summary>
  146. /// <param name="formatIn">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.</param>
  147. /// <param name="formatOut">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.</param>
  148. /// <returns>HRESULT success code.</returns>
  149. int System.Runtime.InteropServices.ComTypes.IDataObject.GetCanonicalFormatEtc(ref FORMATETC formatIn, out FORMATETC formatOut)
  150. {
  151. throw new NotImplementedException();
  152. }
  153. /// <summary>
  154. /// Obtains data from a source data object.
  155. /// </summary>
  156. /// <param name="format">A pointer to a FORMATETC structure that defines the format, medium, and target device to use when passing the data.</param>
  157. /// <param name="medium">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.</param>
  158. [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Method doesn't decrease security.")]
  159. void System.Runtime.InteropServices.ComTypes.IDataObject.GetData(ref FORMATETC format, out STGMEDIUM medium)
  160. {
  161. medium = new STGMEDIUM();
  162. var hr = ((System.Runtime.InteropServices.ComTypes.IDataObject)this).QueryGetData(ref format);
  163. if (NativeMethods.IsSucceededHresult(hr))
  164. {
  165. // Find the best match
  166. var formatCopy = format; // Cannot use ref or out parameter inside an anonymous method, lambda expression, or query expression
  167. var dataObject = _dataObjects
  168. .FirstOrDefault(d => d.Formatetc.cfFormat == formatCopy.cfFormat
  169. && d.Formatetc.dwAspect == formatCopy.dwAspect
  170. && 0 != (d.Formatetc.tymed & formatCopy.tymed)
  171. && d.Formatetc.lindex == formatCopy.lindex);
  172. if (dataObject != null)
  173. {
  174. if (!IsAsynchronous && FILEDESCRIPTORW == dataObject.Formatetc.cfFormat && !_inOperation)
  175. {
  176. // Enter the operation and call the start action
  177. _inOperation = true;
  178. _startAction?.Invoke(this);
  179. }
  180. // Populate the STGMEDIUM
  181. medium.tymed = dataObject.Formatetc.tymed;
  182. var result = dataObject.GetData(); // Possible call to user code
  183. hr = result.Item2;
  184. if (NativeMethods.IsSucceededHresult(hr))
  185. {
  186. medium.unionmember = result.Item1;
  187. }
  188. }
  189. else
  190. {
  191. // Couldn't find a match
  192. hr = NativeMethods.DV_E_FORMATETC;
  193. }
  194. }
  195. if (!NativeMethods.IsSucceededHresult(hr)) // Not redundant; hr gets updated in the block above
  196. {
  197. Marshal.ThrowExceptionForHR(hr);
  198. }
  199. }
  200. /// <summary>
  201. /// Obtains data from a source data object.
  202. /// </summary>
  203. /// <param name="format">A pointer to a FORMATETC structure that defines the format, medium, and target device to use when passing the data.</param>
  204. /// <param name="medium">A STGMEDIUM that defines the storage medium containing the data being transferred.</param>
  205. void System.Runtime.InteropServices.ComTypes.IDataObject.GetDataHere(ref FORMATETC format, ref STGMEDIUM medium)
  206. {
  207. throw new NotImplementedException();
  208. }
  209. /// <summary>
  210. /// Determines whether the data object is capable of rendering the data described in the FORMATETC structure.
  211. /// </summary>
  212. /// <param name="format">A pointer to a FORMATETC structure that defines the format, medium, and target device to use for the query.</param>
  213. /// <returns>HRESULT success code.</returns>
  214. int System.Runtime.InteropServices.ComTypes.IDataObject.QueryGetData(ref FORMATETC format)
  215. {
  216. var formatCopy = format; // Cannot use ref or out parameter inside an anonymous method, lambda expression, or query expression
  217. var formatMatches = _dataObjects.Where(d => d.Formatetc.cfFormat == formatCopy.cfFormat).ToArray();
  218. if (!formatMatches.Any())
  219. {
  220. return NativeMethods.DV_E_FORMATETC;
  221. }
  222. var tymedMatches = formatMatches.Where(d => 0 != (d.Formatetc.tymed & formatCopy.tymed)).ToArray();
  223. if (!tymedMatches.Any())
  224. {
  225. return NativeMethods.DV_E_TYMED;
  226. }
  227. var aspectMatches = tymedMatches.Where(d => d.Formatetc.dwAspect == formatCopy.dwAspect);
  228. if (!aspectMatches.Any())
  229. {
  230. return NativeMethods.DV_E_DVASPECT;
  231. }
  232. return NativeMethods.S_OK;
  233. }
  234. /// <summary>
  235. /// Transfers data to the object that implements this method.
  236. /// </summary>
  237. /// <param name="formatIn">A FORMATETC structure that defines the format used by the data object when interpreting the data contained in the storage medium.</param>
  238. /// <param name="medium">A STGMEDIUM structure that defines the storage medium in which the data is being passed.</param>
  239. /// <param name="release">true to specify that the data object called, which implements SetData, owns the storage medium after the call returns.</param>
  240. [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Method doesn't decrease security.")]
  241. void System.Runtime.InteropServices.ComTypes.IDataObject.SetData(ref FORMATETC formatIn, ref STGMEDIUM medium, bool release)
  242. {
  243. var handled = false;
  244. if (formatIn.dwAspect == DVASPECT.DVASPECT_CONTENT &&
  245. formatIn.tymed == TYMED.TYMED_HGLOBAL &&
  246. medium.tymed == formatIn.tymed)
  247. {
  248. // Supported format; capture the data
  249. var ptr = NativeMethods.GlobalLock(medium.unionmember);
  250. if (IntPtr.Zero != ptr)
  251. {
  252. try
  253. {
  254. var length = NativeMethods.GlobalSize(ptr).ToInt32();
  255. var data = new byte[length];
  256. Marshal.Copy(ptr, data, 0, length);
  257. // Store it in our own format
  258. SetData(formatIn.cfFormat, data);
  259. handled = true;
  260. }
  261. finally
  262. {
  263. NativeMethods.GlobalUnlock(medium.unionmember);
  264. }
  265. }
  266. // Release memory if we now own it
  267. if (release)
  268. {
  269. Marshal.FreeHGlobal(medium.unionmember);
  270. }
  271. }
  272. // Handle synchronous mode
  273. if (!IsAsynchronous && PERFORMEDDROPEFFECT == formatIn.cfFormat && _inOperation)
  274. {
  275. // Call the end action and exit the operation
  276. _endAction?.Invoke(this);
  277. _inOperation = false;
  278. }
  279. // Throw if unhandled
  280. if (!handled)
  281. {
  282. throw new NotImplementedException();
  283. }
  284. }
  285. #endregion IDataObject Members
  286. /// <summary>
  287. /// Provides data for the specified data format (HGLOBAL).
  288. /// </summary>
  289. /// <param name="dataFormat">Data format.</param>
  290. /// <param name="data">Sequence of data.</param>
  291. public void SetData(short dataFormat, IEnumerable<byte> data)
  292. {
  293. _dataObjects.Add(
  294. new DataObject
  295. {
  296. Formatetc = new FORMATETC
  297. {
  298. cfFormat = dataFormat,
  299. ptd = IntPtr.Zero,
  300. dwAspect = DVASPECT.DVASPECT_CONTENT,
  301. lindex = -1,
  302. tymed = TYMED.TYMED_HGLOBAL
  303. },
  304. GetData = () =>
  305. {
  306. var dataArray = data.ToArray();
  307. var ptr = Marshal.AllocHGlobal(dataArray.Length);
  308. Marshal.Copy(dataArray, 0, ptr, dataArray.Length);
  309. return new Tuple<IntPtr, int>(ptr, NativeMethods.S_OK);
  310. },
  311. });
  312. }
  313. /// <summary>
  314. /// Provides data for the specified data format and index (ISTREAM).
  315. /// </summary>
  316. /// <param name="dataFormat">Data format.</param>
  317. /// <param name="index">Index of data.</param>
  318. /// <param name="streamData">Action generating the data.</param>
  319. /// <remarks>
  320. /// Uses Stream instead of IEnumerable(T) because Stream is more likely
  321. /// to be natural for the expected scenarios.
  322. /// </remarks>
  323. public void SetData(short dataFormat, int index, Action<Stream> streamData)
  324. {
  325. _dataObjects.Add(
  326. new DataObject
  327. {
  328. Formatetc = new FORMATETC
  329. {
  330. cfFormat = dataFormat,
  331. ptd = IntPtr.Zero,
  332. dwAspect = DVASPECT.DVASPECT_CONTENT,
  333. lindex = index,
  334. tymed = TYMED.TYMED_ISTREAM
  335. },
  336. GetData = () =>
  337. {
  338. // Create IStream for data
  339. var iStream = NativeMethods.CreateStreamOnHGlobal(IntPtr.Zero, true);
  340. if (streamData != null)
  341. {
  342. // Wrap in a .NET-friendly Stream and call provided code to fill it
  343. using (var stream = new IStreamWrapper(iStream))
  344. {
  345. streamData(stream);
  346. }
  347. }
  348. // Return an IntPtr for the IStream
  349. var ptr = Marshal.GetComInterfaceForObject(iStream, typeof(IStream));
  350. Marshal.ReleaseComObject(iStream);
  351. return new Tuple<IntPtr, int>(ptr, NativeMethods.S_OK);
  352. },
  353. });
  354. }
  355. /// <summary>
  356. /// Provides data for the specified data format (FILEGROUPDESCRIPTOR/FILEDESCRIPTOR)
  357. /// </summary>
  358. /// <param name="fileDescriptors">Collection of virtual files.</param>
  359. public void SetData(IReadOnlyCollection<FileDescriptor> fileDescriptors)
  360. {
  361. // Prepare buffer
  362. var bytes = new List<byte>();
  363. // Add FILEGROUPDESCRIPTOR header
  364. bytes.AddRange(StructureBytes(new NativeMethods.FileGroupDescriptorStruct { cItems = (uint)fileDescriptors.Count() }));
  365. // Add n FILEDESCRIPTORs
  366. foreach (var fileDescriptor in fileDescriptors)
  367. {
  368. // Set required fields
  369. var filedescriptor = new NativeMethods.FileDescriptorStruct
  370. {
  371. cFileName = fileDescriptor.Name,
  372. };
  373. // Set optional timestamp
  374. if (fileDescriptor.ChangeTimeUtc.HasValue)
  375. {
  376. filedescriptor.dwFlags |= NativeMethods.FD_CREATETIME | NativeMethods.FD_WRITESTIME;
  377. var changeTime = fileDescriptor.ChangeTimeUtc.Value.ToLocalTime().ToFileTime();
  378. var changeTimeFileTime = new System.Runtime.InteropServices.ComTypes.FILETIME
  379. {
  380. dwLowDateTime = (int)(changeTime & 0xffffffff),
  381. dwHighDateTime = (int)(changeTime >> 32),
  382. };
  383. filedescriptor.ftLastWriteTime = changeTimeFileTime;
  384. filedescriptor.ftCreationTime = changeTimeFileTime;
  385. }
  386. // Set optional length
  387. if (fileDescriptor.Length.HasValue)
  388. {
  389. filedescriptor.dwFlags |= NativeMethods.FD_FILESIZE;
  390. filedescriptor.nFileSizeLow = (uint)(fileDescriptor.Length & 0xffffffff);
  391. filedescriptor.nFileSizeHigh = (uint)(fileDescriptor.Length >> 32);
  392. }
  393. // Add structure to buffer
  394. bytes.AddRange(StructureBytes(filedescriptor));
  395. }
  396. // Set CFSTR_FILEDESCRIPTORW
  397. SetData(FILEDESCRIPTORW, bytes);
  398. // Set n CFSTR_FILECONTENTS
  399. var index = 0;
  400. foreach (var fileDescriptor in fileDescriptors)
  401. {
  402. SetData(FILECONTENTS, index, fileDescriptor.StreamContents);
  403. index++;
  404. }
  405. }
  406. /// <summary>
  407. /// Gets or sets the CFSTR_PASTESUCCEEDED value for the object.
  408. /// </summary>
  409. public DragDropEffects? PasteSucceeded
  410. {
  411. get => GetDropEffect(PASTESUCCEEDED);
  412. set => SetData(PASTESUCCEEDED, BitConverter.GetBytes((uint)(value ?? DragDropEffects.None)));
  413. }
  414. /// <summary>
  415. /// Gets or sets the CFSTR_PERFORMEDDROPEFFECT value for the object.
  416. /// </summary>
  417. public DragDropEffects? PerformedDropEffect
  418. {
  419. get => GetDropEffect(PERFORMEDDROPEFFECT);
  420. set => SetData(PERFORMEDDROPEFFECT, BitConverter.GetBytes((uint)(value ?? DragDropEffects.None)));
  421. }
  422. /// <summary>
  423. /// Gets or sets the CFSTR_PREFERREDDROPEFFECT value for the object.
  424. /// </summary>
  425. public DragDropEffects? PreferredDropEffect
  426. {
  427. get => GetDropEffect(PREFERREDDROPEFFECT);
  428. set => SetData(PREFERREDDROPEFFECT, BitConverter.GetBytes((uint)(value ?? DragDropEffects.None)));
  429. }
  430. /// <summary>
  431. /// Gets the DragDropEffects value (if any) previously set on the object.
  432. /// </summary>
  433. /// <param name="format">Clipboard format.</param>
  434. /// <returns>DragDropEffects value or null.</returns>
  435. [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Method doesn't decrease security.")]
  436. private DragDropEffects? GetDropEffect(short format)
  437. {
  438. // Get the most recent setting
  439. var dataObject = _dataObjects
  440. .LastOrDefault(d =>
  441. format == d.Formatetc.cfFormat &&
  442. DVASPECT.DVASPECT_CONTENT == d.Formatetc.dwAspect &&
  443. TYMED.TYMED_HGLOBAL == d.Formatetc.tymed);
  444. if (null != dataObject)
  445. {
  446. // Read the value and return it
  447. var result = dataObject.GetData();
  448. if (NativeMethods.IsSucceededHresult(result.Item2))
  449. {
  450. var ptr = NativeMethods.GlobalLock(result.Item1);
  451. if (IntPtr.Zero != ptr)
  452. {
  453. try
  454. {
  455. var length = NativeMethods.GlobalSize(ptr).ToInt32();
  456. if (4 == length)
  457. {
  458. var data = new byte[length];
  459. Marshal.Copy(ptr, data, 0, length);
  460. return (DragDropEffects)BitConverter.ToUInt32(data, 0);
  461. }
  462. }
  463. finally
  464. {
  465. NativeMethods.GlobalUnlock(result.Item1);
  466. }
  467. }
  468. }
  469. }
  470. return null;
  471. }
  472. #region IAsyncOperation Members
  473. // Explicit interface implementation hides the technical details from users of VirtualFileDataObject.
  474. /// <summary>
  475. /// Called by a drop source to specify whether the data object supports asynchronous data extraction.
  476. /// </summary>
  477. /// <param name="fDoOpAsync">A Boolean value that is set to VARIANT_TRUE to indicate that an asynchronous operation is supported, or VARIANT_FALSE otherwise.</param>
  478. void IAsyncOperation.SetAsyncMode(int fDoOpAsync)
  479. {
  480. IsAsynchronous = !(NativeMethods.VARIANT_FALSE == fDoOpAsync);
  481. }
  482. /// <summary>
  483. /// Called by a drop target to determine whether the data object supports asynchronous data extraction.
  484. /// </summary>
  485. /// <param name="pfIsOpAsync">A Boolean value that is set to VARIANT_TRUE to indicate that an asynchronous operation is supported, or VARIANT_FALSE otherwise.</param>
  486. void IAsyncOperation.GetAsyncMode(out int pfIsOpAsync)
  487. {
  488. pfIsOpAsync = IsAsynchronous ? NativeMethods.VARIANT_TRUE : NativeMethods.VARIANT_FALSE;
  489. }
  490. /// <summary>
  491. /// Called by a drop target to indicate that asynchronous data extraction is starting.
  492. /// </summary>
  493. /// <param name="pbcReserved">Reserved. Set this value to NULL.</param>
  494. void IAsyncOperation.StartOperation(IBindCtx pbcReserved)
  495. {
  496. _inOperation = true;
  497. _startAction?.Invoke(this);
  498. }
  499. /// <summary>
  500. /// Called by the drop source to determine whether the target is extracting data asynchronously.
  501. /// </summary>
  502. /// <param name="pfInAsyncOp">Set to VARIANT_TRUE if data extraction is being handled asynchronously, or VARIANT_FALSE otherwise.</param>
  503. void IAsyncOperation.InOperation(out int pfInAsyncOp)
  504. {
  505. pfInAsyncOp = _inOperation ? NativeMethods.VARIANT_TRUE : NativeMethods.VARIANT_FALSE;
  506. }
  507. /// <summary>
  508. /// Notifies the data object that that asynchronous data extraction has ended.
  509. /// </summary>
  510. /// <param name="hResult">An HRESULT value that indicates the outcome of the data extraction. Set to S_OK if successful, or a COM error code otherwise.</param>
  511. /// <param name="pbcReserved">Reserved. Set to NULL.</param>
  512. /// <param name="dwEffects">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.</param>
  513. void IAsyncOperation.EndOperation(int hResult, IBindCtx pbcReserved, uint dwEffects)
  514. {
  515. _endAction?.Invoke(this);
  516. _inOperation = false;
  517. }
  518. #endregion IAsyncOperation Members
  519. /// <summary>
  520. /// Returns the in-memory representation of an interop structure.
  521. /// </summary>
  522. /// <param name="source">Structure to return.</param>
  523. /// <returns>In-memory representation of structure.</returns>
  524. [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Method doesn't decrease security.")]
  525. private static IEnumerable<byte> StructureBytes(object source)
  526. {
  527. // Set up for call to StructureToPtr
  528. var size = Marshal.SizeOf(source.GetType());
  529. var ptr = Marshal.AllocHGlobal(size);
  530. var bytes = new byte[size];
  531. try
  532. {
  533. Marshal.StructureToPtr(source, ptr, false);
  534. // Copy marshalled bytes to buffer
  535. Marshal.Copy(ptr, bytes, 0, size);
  536. }
  537. finally
  538. {
  539. Marshal.FreeHGlobal(ptr);
  540. }
  541. return bytes;
  542. }
  543. /// <summary>
  544. /// Class representing a virtual file for use by drag/drop or the clipboard.
  545. /// </summary>
  546. [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Justification = "Deliberate to provide obvious coupling.")]
  547. public class FileDescriptor
  548. {
  549. /// <summary>
  550. /// Gets or sets the name of the file.
  551. /// </summary>
  552. public string Name { get; set; }
  553. /// <summary>
  554. /// Gets or sets the (optional) length of the file.
  555. /// </summary>
  556. public long? Length { get; set; }
  557. /// <summary>
  558. /// Gets or sets the (optional) change time of the file.
  559. /// </summary>
  560. public DateTime? ChangeTimeUtc { get; set; }
  561. /// <summary>
  562. /// Gets or sets an Action that returns the contents of the file.
  563. /// </summary>
  564. public Action<Stream> StreamContents { get; set; }
  565. }
  566. /// <summary>
  567. /// Class representing the result of a SetData call.
  568. /// </summary>
  569. private class DataObject
  570. {
  571. /// <summary>
  572. /// FORMATETC structure for the data.
  573. /// </summary>
  574. public FORMATETC Formatetc { get; set; }
  575. /// <summary>
  576. /// Func returning the data as an IntPtr and an HRESULT success code.
  577. /// </summary>
  578. public Func<Tuple<IntPtr, int>> GetData { get; set; }
  579. }
  580. /// <summary>
  581. /// Represents a 2-tuple, or pair.
  582. /// </summary>
  583. /// <remarks>
  584. /// Minimal implementation of the .NET 4 Tuple class; remove if running on .NET 4.
  585. /// </remarks>
  586. /// <typeparam name="T1">The type of the tuple's first component.</typeparam>
  587. /// <typeparam name="T2">The type of the tuple's second component.</typeparam>
  588. private class Tuple<T1, T2>
  589. {
  590. /// <summary>
  591. /// Gets the value of the current Tuple(T1, T2) object's first component.
  592. /// </summary>
  593. public T1 Item1 { get; }
  594. /// <summary>
  595. /// Gets the value of the current Tuple(T1, T2) object's second component.
  596. /// </summary>
  597. public T2 Item2 { get; }
  598. /// <summary>
  599. /// Initializes a new instance of the Tuple(T1, T2) class.
  600. /// </summary>
  601. /// <param name="item1">The value of the tuple's first component.</param>
  602. /// <param name="item2">The value of the tuple's second component.</param>
  603. public Tuple(T1 item1, T2 item2)
  604. {
  605. Item1 = item1;
  606. Item2 = item2;
  607. }
  608. }
  609. /// <summary>
  610. /// Simple class that exposes a write-only IStream as a Stream.
  611. /// </summary>
  612. private class IStreamWrapper : Stream
  613. {
  614. /// <summary>
  615. /// IStream instance being wrapped.
  616. /// </summary>
  617. private readonly IStream _iStream;
  618. /// <summary>
  619. /// Initializes a new instance of the IStreamWrapper class.
  620. /// </summary>
  621. /// <param name="iStream">IStream instance to wrap.</param>
  622. public IStreamWrapper(IStream iStream)
  623. {
  624. _iStream = iStream;
  625. }
  626. /// <summary>
  627. /// Gets a value indicating whether the current stream supports reading.
  628. /// </summary>
  629. public override bool CanRead => false;
  630. /// <summary>
  631. /// Gets a value indicating whether the current stream supports seeking.
  632. /// </summary>
  633. public override bool CanSeek => false;
  634. /// <summary>
  635. /// Gets a value indicating whether the current stream supports writing.
  636. /// </summary>
  637. public override bool CanWrite => true;
  638. /// <summary>
  639. /// Clears all buffers for this stream and causes any buffered data to be written to the underlying device.
  640. /// </summary>
  641. public override void Flush()
  642. {
  643. throw new NotImplementedException();
  644. }
  645. /// <summary>
  646. /// Gets the length in bytes of the stream.
  647. /// </summary>
  648. public override long Length => throw new NotImplementedException();
  649. /// <summary>
  650. /// Gets or sets the position within the current stream.
  651. /// </summary>
  652. public override long Position
  653. {
  654. get => throw new NotImplementedException();
  655. set => throw new NotImplementedException();
  656. }
  657. /// <summary>
  658. /// Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.
  659. /// </summary>
  660. /// <param name="buffer">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.</param>
  661. /// <param name="offset">The zero-based byte offset in buffer at which to begin storing the data read from the current stream.</param>
  662. /// <param name="count">The maximum number of bytes to be read from the current stream.</param>
  663. /// <returns>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.</returns>
  664. public override int Read(byte[] buffer, int offset, int count)
  665. {
  666. throw new NotImplementedException();
  667. }
  668. /// <summary>
  669. /// Sets the position within the current stream.
  670. /// </summary>
  671. /// <param name="offset">A byte offset relative to the origin parameter.</param>
  672. /// <param name="origin">A value of type SeekOrigin indicating the reference point used to obtain the new position.</param>
  673. /// <returns>The new position within the current stream.</returns>
  674. public override long Seek(long offset, SeekOrigin origin)
  675. {
  676. throw new NotImplementedException();
  677. }
  678. /// <summary>
  679. /// Sets the length of the current stream.
  680. /// </summary>
  681. /// <param name="value">The desired length of the current stream in bytes.</param>
  682. public override void SetLength(long value)
  683. {
  684. throw new NotImplementedException();
  685. }
  686. /// <summary>
  687. /// Writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.
  688. /// </summary>
  689. /// <param name="buffer">An array of bytes. This method copies count bytes from buffer to the current stream.</param>
  690. /// <param name="offset">The zero-based byte offset in buffer at which to begin copying bytes to the current stream.</param>
  691. /// <param name="count">The number of bytes to be written to the current stream.</param>
  692. public override void Write(byte[] buffer, int offset, int count)
  693. {
  694. _iStream.Write(
  695. offset == 0 ? buffer : buffer.Skip(offset).ToArray(),
  696. count,
  697. IntPtr.Zero);
  698. }
  699. }
  700. /// <summary>
  701. /// Initiates a drag-and-drop operation.
  702. /// </summary>
  703. /// <param name="dragSource">A reference to the dependency object that is the source of the data being dragged.</param>
  704. /// <param name="dataObject">A data object that contains the data being dragged.</param>
  705. /// <param name="allowedEffects">One of the DragDropEffects values that specifies permitted effects of the drag-and-drop operation.</param>
  706. /// <returns>One of the DragDropEffects values that specifies the final effect that was performed during the drag-and-drop operation.</returns>
  707. /// <remarks>
  708. /// Call this method instead of System.Windows.DragDrop.DoDragDrop because this method handles IDataObject better.
  709. /// </remarks>
  710. [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "dragSource", Justification = "Parameter is present so the signature matches that of System.Windows.DragDrop.DoDragDrop.")]
  711. public static DragDropEffects DoDragDrop(System.Runtime.InteropServices.ComTypes.IDataObject dataObject, DragDropEffects allowedEffects)
  712. {
  713. int[] finalEffect = new int[1];
  714. try
  715. {
  716. NativeMethods.DoDragDrop(dataObject, new DropSource(), (int)allowedEffects, finalEffect);
  717. }
  718. finally
  719. {
  720. if (dataObject is VirtualFileDataObject virtualFileDataObject && !virtualFileDataObject.IsAsynchronous && virtualFileDataObject._inOperation)
  721. {
  722. // Call the end action and exit the operation
  723. virtualFileDataObject._endAction?.Invoke(virtualFileDataObject);
  724. virtualFileDataObject._inOperation = false;
  725. }
  726. }
  727. return (DragDropEffects)finalEffect[0];
  728. }
  729. /// <summary>
  730. /// Contains the methods for generating visual feedback to the end user and for canceling or completing the drag-and-drop operation.
  731. /// </summary>
  732. private class DropSource : NativeMethods.IDropSource
  733. {
  734. /// <summary>
  735. /// Determines whether a drag-and-drop operation should continue.
  736. /// </summary>
  737. /// <param name="fEscapePressed">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.</param>
  738. /// <param name="grfKeyState">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.</param>
  739. /// <returns>This method returns S_OK/DRAGDROP_S_DROP/DRAGDROP_S_CANCEL on success.</returns>
  740. public int QueryContinueDrag(int fEscapePressed, uint grfKeyState)
  741. {
  742. var escapePressed = 0 != fEscapePressed;
  743. var keyStates = (DragDropKeyStates)grfKeyState;
  744. if (escapePressed)
  745. {
  746. return NativeMethods.DRAGDROP_S_CANCEL;
  747. }
  748. else if (DragDropKeyStates.None == (keyStates & DragDropKeyStates.LeftMouseButton))
  749. {
  750. return NativeMethods.DRAGDROP_S_DROP;
  751. }
  752. return NativeMethods.S_OK;
  753. }
  754. /// <summary>
  755. /// Gives visual feedback to an end user during a drag-and-drop operation.
  756. /// </summary>
  757. /// <param name="dwEffect">The DROPEFFECT value returned by the most recent call to IDropTarget::DragEnter, IDropTarget::DragOver, or IDropTarget::DragLeave. </param>
  758. /// <returns>This method returns S_OK on success.</returns>
  759. public int GiveFeedback(uint dwEffect)
  760. {
  761. return NativeMethods.DRAGDROP_S_USEDEFAULTCURSORS;
  762. }
  763. }
  764. /// <summary>
  765. /// Provides access to Win32-level constants, structures, and functions.
  766. /// </summary>
  767. private static class NativeMethods
  768. {
  769. // ReSharper disable UnusedMember.Local
  770. // ReSharper disable UnusedMember.Global
  771. public const int DRAGDROP_S_DROP = 0x00040100;
  772. public const int DRAGDROP_S_CANCEL = 0x00040101;
  773. public const int DRAGDROP_S_USEDEFAULTCURSORS = 0x00040102;
  774. public const int DV_E_DVASPECT = -2147221397;
  775. public const int DV_E_FORMATETC = -2147221404;
  776. public const int DV_E_TYMED = -2147221399;
  777. public const int E_FAIL = -2147467259;
  778. public const uint FD_CREATETIME = 0x00000008;
  779. public const uint FD_WRITESTIME = 0x00000020;
  780. public const uint FD_FILESIZE = 0x00000040;
  781. public const int OLE_E_ADVISENOTSUPPORTED = -2147221501;
  782. public const int S_OK = 0;
  783. public const int S_FALSE = 1;
  784. public const int VARIANT_FALSE = 0;
  785. public const int VARIANT_TRUE = -1;
  786. public const string CFSTR_FILECONTENTS = "FileContents";
  787. public const string CFSTR_FILEDESCRIPTORW = "FileGroupDescriptorW";
  788. public const string CFSTR_PASTESUCCEEDED = "Paste Succeeded";
  789. public const string CFSTR_PERFORMEDDROPEFFECT = "Performed DropEffect";
  790. public const string CFSTR_PREFERREDDROPEFFECT = "Preferred DropEffect";
  791. // ReSharper restore UnusedMember.Global
  792. // ReSharper restore UnusedMember.Local
  793. [SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "Structure exists for interop.")]
  794. [StructLayout(LayoutKind.Sequential)]
  795. public struct FileGroupDescriptorStruct
  796. {
  797. public uint cItems;
  798. // Followed by 0 or more FILEDESCRIPTORs
  799. }
  800. [SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "Structure exists for interop.")]
  801. [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
  802. public struct FileDescriptorStruct
  803. {
  804. public uint dwFlags;
  805. public readonly Guid clsid;
  806. public readonly int sizelcx;
  807. public readonly int sizelcy;
  808. public readonly int pointlx;
  809. public readonly int pointly;
  810. public readonly uint dwFileAttributes;
  811. public System.Runtime.InteropServices.ComTypes.FILETIME ftCreationTime;
  812. public readonly System.Runtime.InteropServices.ComTypes.FILETIME ftLastAccessTime;
  813. public System.Runtime.InteropServices.ComTypes.FILETIME ftLastWriteTime;
  814. public uint nFileSizeHigh;
  815. public uint nFileSizeLow;
  816. [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
  817. public string cFileName;
  818. }
  819. [ComImport]
  820. [Guid("00000121-0000-0000-C000-000000000046")]
  821. [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
  822. public interface IDropSource
  823. {
  824. [PreserveSig]
  825. int QueryContinueDrag(int fEscapePressed, uint grfKeyState);
  826. [PreserveSig]
  827. int GiveFeedback(uint dwEffect);
  828. }
  829. [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "2#", Justification = "Win32 API.")]
  830. [DllImport("shell32.dll")]
  831. public static extern int SHCreateStdEnumFmtEtc(uint cfmt, FORMATETC[] afmt, out IEnumFORMATETC ppenumFormatEtc);
  832. [return: MarshalAs(UnmanagedType.Interface)]
  833. [DllImport("ole32.dll", PreserveSig = false)]
  834. public static extern IStream CreateStreamOnHGlobal(IntPtr hGlobal, [MarshalAs(UnmanagedType.Bool)] bool fDeleteOnRelease);
  835. [DllImport("ole32.dll", CharSet = CharSet.Auto, ExactSpelling = true, PreserveSig = false)]
  836. public static extern void DoDragDrop(System.Runtime.InteropServices.ComTypes.IDataObject dataObject, IDropSource dropSource, int allowedEffects, int[] finalEffect);
  837. [DllImport("kernel32.dll")]
  838. public static extern IntPtr GlobalLock(IntPtr hMem);
  839. [return: MarshalAs(UnmanagedType.Bool)]
  840. [DllImport("kernel32.dll")]
  841. public static extern bool GlobalUnlock(IntPtr hMem);
  842. [DllImport("kernel32.dll")]
  843. public static extern IntPtr GlobalSize(IntPtr handle);
  844. /// <summary>
  845. /// Returns true iff the HRESULT is a success code.
  846. /// </summary>
  847. /// <param name="hr">HRESULT to check.</param>
  848. /// <returns>True iff a success code.</returns>
  849. public static bool IsSucceededHresult(int hr)
  850. {
  851. return 0 <= hr;
  852. }
  853. }
  854. }
  855. /// <summary>
  856. /// Definition of the IAsyncOperation COM interface.
  857. /// </summary>
  858. /// <remarks>
  859. /// Pseudo-public because VirtualFileDataObject implements it.
  860. /// </remarks>
  861. [ComImport]
  862. [Guid("3D8B0590-F691-11d2-8EA9-006097DF5BD4")]
  863. [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
  864. internal interface IAsyncOperation
  865. {
  866. void SetAsyncMode([In] int fDoOpAsync);
  867. void GetAsyncMode([Out] out int pfIsOpAsync);
  868. void StartOperation([In] IBindCtx pbcReserved);
  869. void InOperation([Out] out int pfInAsyncOp);
  870. void EndOperation([In] int hResult, [In] IBindCtx pbcReserved, [In] uint dwEffects);
  871. }
  872. }