Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
775 views
in Technique[技术] by (71.8m points)

.net - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:empest1.txt", @"c:empest2.txt" };
        StartCopyFiles(files, true);

Pressing Ctrl+V in Windows Explorer copied the files from my c:emp 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...