I am trying to create a windows form onto which I can drop a file/folder.
I have the following code in a WinForms app
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_DragEnter(object sender, DragEventArgs e)
{
Debug.Print("DragEnter");
}
private void Form1_DragDrop(object sender, DragEventArgs e)
{
MessageBox.Show("Dropped!");
}
}
I have set the AllowDrop property to true.
I've tried running the application in debug within Visual Studio.
Based on answers to other similar questions, I've tried running the compiled exe as administrator.
I've tried running the compiled exe not as administrator.
But whatever I do, I cannot get the DragDrop event to fire. The DragEnter event does fire, however. What am I missing?
Is your DragDropEffect
set appropriately? Try placing this in the DragEnter Event Handler Method:
private void Form1_DragEnter(object sender, DragEventArgs e)
{
Console.WriteLine("DragEnter!");
e.Effect = DragDropEffects.Copy;
}
By default it was set to DragDropEffects.None
so the Drop event wouldn't fire.
For those who would read this because tips above do not work.
Notice that Drag&Drop won't work if you run Visual Studio or your app "As Administrator" as reported here: https://visualstudio.uservoice.com/forums/121579-visual-studio-ide/suggestions/2164233-fix-drag-and-drop-to-open-file-when-running-as-adm
try to use something like this in your Form1_DragEnter:
private void Form1_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
e.Effect = DragDropEffects.All;
else
{
String[] strGetFormats = e.Data.GetFormats();
e.Effect = DragDropEffects.None;
}
}
this fires your Form1_DragDrop
Don't forget in properties of the form to change AllowDrop to "True" Your code is probably fine but if this property is not enabled to true it won't work. It is set to false by default.
Have you written the MouseDown and MouseMove events of the object you are dragging from.
Another very nasty and tricky problem can be that you have overriden OnHandleCreated
, but forgot to call the base implementation. Then your application fails to set the required internal window settings to respect your AllowDrop
property.
E.g., make sure to call base.OnHandleCreated(e)
in your override, and you'll be fine.
I also had this perplexing issue despite the form having AllowDrop set to true!
In my Windows Forms app (VS2017) I had to make sure I had set a valid Startup object: e.g myprojectname.Program and all was fine!
I had a command line specified that was pointing to a file that no longer existed. Somehow that was preventing drag enter from firing. Once I removed it everything was fine again.