|
| 1 | +// Copyright (c) Files Community |
| 2 | +// Licensed under the MIT License. |
| 3 | + |
| 4 | +using System.Runtime.CompilerServices; |
| 5 | +using Windows.Win32; |
| 6 | +using Windows.Win32.Foundation; |
| 7 | +using Windows.Win32.System.Com; |
| 8 | +using Windows.Win32.UI.Shell; |
| 9 | + |
| 10 | +namespace Files.App.Storage.Storables |
| 11 | +{ |
| 12 | + public sealed class WindowsBulkOperations : IDisposable |
| 13 | + { |
| 14 | + // Constants |
| 15 | + |
| 16 | + private const FILEOPERATION_FLAGS defaultOptions = FILEOPERATION_FLAGS.FOF_ALLOWUNDO | FILEOPERATION_FLAGS.FOF_NOCONFIRMMKDIR; |
| 17 | + |
| 18 | + // Fields |
| 19 | + |
| 20 | + private readonly ComPtr<IFileOperation> _pFileOperation; |
| 21 | + private readonly ComPtr<IFileOperationProgressSink> _pProgressSink; |
| 22 | + private readonly uint _progressSinkCookie; |
| 23 | + |
| 24 | + private int _disposedValue = 0; |
| 25 | + private FILEOPERATION_FLAGS _operationFlags = defaultOptions; |
| 26 | + private HWND _owner; |
| 27 | + |
| 28 | + // Constructor |
| 29 | + |
| 30 | + public unsafe WindowsBulkOperations(HWND owner = default) |
| 31 | + { |
| 32 | + var clsid = typeof(FileOperation).GUID; |
| 33 | + var iid = typeof(IFileOperation).GUID; |
| 34 | + void* pObj = default; |
| 35 | + |
| 36 | + PInvoke.CoCreateInstance( |
| 37 | + &clsid, |
| 38 | + null, |
| 39 | + CLSCTX.CLSCTX_LOCAL_SERVER, |
| 40 | + &iid, |
| 41 | + (void**)_pFileOperation.GetAddressOf()); |
| 42 | + |
| 43 | + _owner = owner; |
| 44 | + if (owner != default) |
| 45 | + _pFileOperation.Get()->SetOwnerWindow(owner); |
| 46 | + |
| 47 | + _pProgressSink = default; |
| 48 | + _pFileOperation.Get()->Advise(_pProgressSink.Get(), out var progressSinkCookie); |
| 49 | + _progressSinkCookie = progressSinkCookie; |
| 50 | + } |
| 51 | + |
| 52 | + public unsafe HRESULT CopyItem(ComPtr<IShellItem> psiItem, ComPtr<IShellItem> psiDestinationFolder, PWSTR pszCopyName) |
| 53 | + { |
| 54 | + HRESULT hr = default; |
| 55 | + |
| 56 | + try |
| 57 | + { |
| 58 | + hr = _pFileOperation.Get()->CopyItem(psiItem.Get(), psiDestinationFolder.Get(), pszCopyName, _pProgressSink.Get()); |
| 59 | + hr = _pFileOperation.Get()->PerformOperations(); |
| 60 | + hr.ThrowOnFailure(); |
| 61 | + } |
| 62 | + finally |
| 63 | + { |
| 64 | + |
| 65 | + } |
| 66 | + |
| 67 | + return hr; |
| 68 | + } |
| 69 | + |
| 70 | + public void Dispose() |
| 71 | + { |
| 72 | + _pFileOperation.Dispose(); |
| 73 | + _pProgressSink.Dispose(); |
| 74 | + } |
| 75 | + } |
| 76 | +} |
0 commit comments