开发者

Cut files to clipboard in C#

I'm looking for a way to programmatically cut a file to the clipboard, for example, some call to a function in C# that does the same as selecting a file in the Windows Explorer and pressing Ctrl + X.

After running the program and pressing Ctrl + V in some other folder on the hard drive, the original file would be moved to the new folder. By looking at Stack Overf开发者_StackOverflow中文版low question Copy files to clipboard in C#, I know that it's easy to do the copy job, but cutting seems to work different. How can I do this?


Please try the following, translated from The Code Project article Setting the Clipboard File DropList with DropEffect in VB.NET:

byte[] moveEffect = new byte[] {2, 0, 0, 0};
MemoryStream dropEffect = new MemoryStream();
dropEffect.Write(moveEffect, 0, moveEffect.Length);

DataObject data = new DataObject();
data.SetFileDropList(files);
data.SetData("Preferred DropEffect", dropEffect);

Clipboard.Clear();
Clipboard.SetDataObject(data, true);


Just to see what happens, I replaced the MemoryStream with a DragDropEffects like this:

data.SetData("FileDrop", files);
data.SetData("Preferred DropEffect", DragDropEffects.Move);

Apparently, it works as a genuine cut rather than a copy! (This was on Windows 7 - I have not tried other operating systems). Unfortunately, it works only coincidentally. For example,

data.SetData("Preferred DropEffect", DragDropEffects.Copy);

does not yield a copy (still a cut). It seems that a non-null causes a cut, a null a copy.


I like to wrap code like this in an API that makes sense. I also like to avoid magic strings of bytes where I can.

I came up with this extension method that solves the mystery that @Keith was facing in his answer, effectively using the DragDropEffects enum.

public static class Extensions
{
    public static void PutFilesOnClipboard(this IEnumerable<FileSystemInfo> filesAndFolders, bool moveFilesOnPaste = false)
    {
        var dropEffect = moveFilesOnPaste ? DragDropEffects.Move : DragDropEffects.Copy;

        var droplist = new StringCollection();
        droplist.AddRange(filesAndFolders.Select(x=>x.FullName).ToArray());     

        var data = new DataObject();
        data.SetFileDropList(droplist);
        data.SetData("Preferred Dropeffect", new MemoryStream(BitConverter.GetBytes((int)dropEffect)));
        Clipboard.SetDataObject(data);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜