I was surprised how easy it is to enable your application to allow dragging things (eg. text or images) from the application to the desktop.
Basically, you create a temporary file with the content in your application, create a DataObject out of it, perform the DoDragDrop and then delete the temporary file.
Here are two snippets (one for WPF, one for WinForms) to show you this. Just call them somewhere (for example in a MousDown event of on a button click).
WPF
private void DragText() { // Create temp file var tempFilePath = Path.Combine(Path.GetTempPath(), String.Format("{0}.txt", "test")); File.WriteAllText(tempFilePath, "Hello world!"); // Prepare the data object string[] files = { tempFilePath }; var data = new DataObject(DataFormats.FileDrop, files); data.SetData(DataFormats.Text, files[0]); // Perform dragdrop DragDrop.DoDragDrop(this, data, DragDropEffects.Copy); // Delete the temp file File.Delete(tempFilePath); }
WinForms
private void DragImage() { // Create temp file var tempFilePath = Path.Combine(Path.GetTempPath(), String.Format("{0}.jpg", "test")); pictureBox1.Image.Save(tempFilePath, ImageFormat.Jpeg); // Prepare the data object string[] files = { tempFilePath }; var data = new DataObject(DataFormats.FileDrop, files); data.SetData(DataFormats.Text, files[0]); // Perform dragdrop DoDragDrop(data, DragDropEffects.Copy); // Delete the temp file File.Delete(tempFilePath); }
#
WPF application not works for this code when i drag to explorer or folder , but winforms works, any idea, windows 10
#
Hi,
3
4
5
6
7
8
9
10
11
12
13
14
private void DragImage()
{
// Create temp file
var tempFilePath = Path.Combine(Path.GetTempPath(), String.Format(“{0}.jpg”, “test”));
pictureBox1.Image.Save(tempFilePath, ImageFormat.Jpeg);
// Prepare the data object
string[] files = { tempFilePath };
var data = new DataObject(DataFormats.FileDrop, files);
data.SetData(DataFormats.Text, files[0]);
// Perform dragdrop
DoDragDrop(data, DragDropEffects.Copy);
// Delete the temp file
File.Delete(tempFilePath);
}
i have done same as shown..but temp file is getting created in the specified path. but not dropping the file to desktop. Please help