Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

  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 and press Ctrl + V - the files are pasted?

  2. If I copy or cut some files/folders in Windows Explorer, how do I get this information (full names and whether they were cut or copied) in my program?

I program in C# 4.0, but other languages' ways are also interesting to know.

like image 701
Ivan Avatar asked May 22 '10 20:05

Ivan


3 Answers

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.

like image 61
Hans Passant Avatar answered Oct 17 '22 05:10

Hans Passant


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.

like image 32
Hans Olsson Avatar answered Oct 17 '22 04:10

Hans Olsson


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

like image 1
Gman Avatar answered Oct 17 '22 04:10

Gman