How to programmatically cut/copy/get files to/from the Windows clipboard in a system standard compliant form?

后端 未结 3 1380
渐次进展
渐次进展 2020-12-17 04:37
  1. How do I put a cut/copy reference to specific files and/or folders into the Windows clipboard so that when I open standard Windows Explorer window, go to somewhere

相关标签:
3条回答
  • 2020-12-17 04:56

    Look at this answer which describes working Cut operation. (Change 2 into 5 for the Copy operation.)

    0 讨论(0)
  • 2020-12-17 04:58

    I've got the 90% solution, reverse-engineered from the clipboard formats and my answer in this thread. You'll need to set two pieces of clipboard data. The list of files, that's easy to do. And another clipboard format named "Preferred Dropeffect" that indicates whether a copy or a move of the files is requested. Leading to this code:

        public static void StartCopyFiles(IList<string> files, bool copy) {
            var obj = new DataObject();
            // File list first
            var coll = new System.Collections.Specialized.StringCollection();
            coll.AddRange(files.ToArray());
            obj.SetFileDropList(coll);
            // Then the operation
            var strm = new System.IO.MemoryStream();
            strm.WriteByte(copy ? (byte)DragDropEffects.Copy : (byte)DragDropEffects.Move);
            obj.SetData("Preferred Dropeffect", strm);
            Clipboard.SetDataObject(obj);
        }
    

    Sample usage:

            var files = new List<string>() { @"c:\temp\test1.txt", @"c:\temp\test2.txt" };
            StartCopyFiles(files, true);
    

    Pressing Ctrl+V in Windows Explorer copied the files from my c:\temp directory.

    What I could not get going is the "cut" operation, passing false to StartCopyFiles() produced a copy operation, the original files where not removed from the source directory. No idea why, should have worked. I reckon that the actual stream format of "Preferred DropEffects" is fancier, probably involving the infamous PIDLs.

    0 讨论(0)
  • 2020-12-17 05:14

    If you're using Windows Forms, look at System.Windows.Forms.Clipboard. I think that should be able to do that. I'm not sure how to do what you want since I've never looked in to it, but I'd look at the FileDropList methods (GetFileDropList, etc.) first since they look promising.

    If you need to find out if it was a copy or a cut and similar more detailed information, it seems like you'll have to use the IDataObject interface.

    0 讨论(0)
提交回复
热议问题