Pages

Saturday, May 16, 2020

Getting the Clipboard File DropEffect in CSharp (C#)

How to access the file DropEffect in c# in order to tell cut from paste for a file DropList.

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 DragDropEffects enum CUT (Move) & PASTE (copy)
 }
 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); //
}
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