Cut files to clipboard in C#

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-27 22:59:48
Dark Falcon

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);
Keith

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);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!