Friday, May 15, 2020

CSharp How to get Clipboard incoming DragDropEffects for FileDrop and set in back

This is a C# working implementation of getting and setting DropEffect for a FileDrop to and from the Clipboard. 

Here's a snippet from the DragDropEffect documentation
https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.dragdropeffects


All-2147483645
The combination of the CopyMove, and Scroll effects.
Copy1
The data from the drag source is copied to the drop target.
4
The data from the drag source is linked to the drop target.
Move2
The data from the drag source is moved to the drop target.
None0
The drop target does not accept the data.
Scroll-2147483648
The target can be scrolled while dragging to locate a drop position that is not currently visible in the target.




string[] fileList = iData.GetData(DataFormats.FileDrop) as string[];
Object objDropEffect = Clipboard.GetData("Preferred DropEffect"); //get drop effect that was put on keyboard
DragDropEffects dropEffect = DragDropEffects.Copy; //set default 
int dropme = 0; //https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.dragdropeffects?view=netcore-3.1

if (objDropEffect.GetType() == typeof(MemoryStream)) //casting check
{ 
 MemoryStream ms = new MemoryStream();  
 try
 {
  ms = (MemoryStream)objDropEffect; //cast should be safe now
  dropme = ms.ReadByte(); //we read first byte of internal _buffer of this object objDropEffect which is 4 element byte array
  dropEffect = (DragDropEffects)dropme; //cast into enum 
 }
 catch 
 {}
 finally 
 {
  ms.Dispose(); //we cannot use a using statement because of casting (MemoryStream)
 }

}

StringCollection strcolFileList = new StringCollection();
strcolFileList.AddRange(fileList);

try
{
        dataObj.SetFileDropList(strcolFileList);
        dataObj.SetData("Preferred DropEffect", dropEffect); //on Win7, this might have to be null to perform a copy
}
catch {}

//https://csharp.hotexamples.com/site/file?hash=0xe453aa34f981d998492adf71d35b84904e1c92052c44966d047a6e8da3c6a81e&fullName=Other/Altaxo/AltaxoSource-0.54.0.554/AltaxoSource/Libraries/ICSharpCode.TextEditor/Project/Src/TextAreaClipboardHandler.cs&project=xuchuansheng/GenXSource
// Work around ExternalException bug. (SD2-426)
// Best reproducable inside Virtual PC.
try
{
 Clipboard.SetDataObject(dataObj);
}
catch (ExternalException)
{
 Application.DoEvents();
 try
 {
  Clipboard.SetDataObject(dataObj);
 }
 catch (ExternalException)
 {
     string error= "Drag'n Drop failed to be set.";
  
 }
}
catch
{
 string error = "Drag'n Drop failed to be set.";
}

No comments:

Post a Comment