Drag and drop does not work in C # Winforms application

I am trying to create a window form to which I can delete a file / folder.

I have the following code in a WinForms application

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 set the AllowDrop property to true. I tried to run the application in debugging in Visual Studio. Based on answers to other similar questions, I tried to run the compiled exe as administrator. I tried to run the compiled exe not as an administrator.

But no matter what I do, I cannot fire the DragDrop event. However, the DragEnter event fires. What am I missing?

+10
source share
8 answers

Does your DragDropEffect match? Try putting this in the DragEnter event handler method:

  private void Form1_DragEnter(object sender, DragEventArgs e) { Console.WriteLine("DragEnter!"); e.Effect = DragDropEffects.Copy; } 

The default value is DragDropEffects.None , so the Drop event will not fire.

+24
source

For those who will read this, because the tips above do not work.

Note that drag and drop will not work if you run Visual Studio or your “As Administrator” application, as indicated here: https://visualstudio.uservoice.com/forums/121579-visual-studio-ide/suggestions/2164233- fix-drag-and-drop-to-open-file-when-running-as-adm

+12
source

try using something like this in 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 will launch your Form1_DragDrop

+4
source

Do not forget to change AllowDrop to "True" in the form properties. Your code is probably right, but if this property is not included in true, it will not work. The default value is false.

+4
source

You write the MouseDown and MouseMove events of the object from which you drag.

0
source

Another very unpleasant and complex problem may be that you redefined OnHandleCreated but forgot to name the base implementation. Then your application will not be able to set the necessary internal window parameters to respect your AllowDrop property.

For example, make sure you call base.OnHandleCreated(e) in your override, and everything will be fine.

0
source

I also had this confusing issue, even though the AllowDrop parameter was set to true!

In my Windows Forms application (VS2017), I had to make sure that I installed a valid startup object: for example, myprojectname.Program and everything was fine!

0
source

I was given a command line pointing to a file that no longer exists. Somehow, this prevented the drag from entering. As soon as I deleted it, everything was fine again.

0
source

Source: https://habr.com/ru/post/977401/