E.Data.GetDataPresent not working in WinForms drag and drop handler?

I am trying to drag and drop files into my application from the Locate32 program (which is great by the way). Here's what's going on:

e.Data.GetFormats()
{string[7]}
    [0]: "FileDrop"
    [1]: "FileNameW"
    [2]: "FileName"
    [3]: "FileNameMap"
    [4]: "FileNameMapW"
    [5]: "Shell IDList Array"
    [6]: "Shell Object Offsets"
DataFormats.FileDrop
"FileDrop"
e.Data.GetDataPresent(DataFormats.FileDrop)
false

      

Why does it e.Data.GetDataPresent(DataFormats.FileDrop)

return false

while FileDrop is clearly one of the formats listed as "available"?

If I do e.Data.GetData(DataFormats.FileDrop)

, I get a list of chunks of filenames as I should. Also, drag and drop works great in Windows Explorer.

Here is the code for my DragEnter handler:

private void MyForm_DragEnter(object sender, DragEventArgs e) {
    if(e.Data.GetDataPresent(DataFormats.FileDrop)) {
        e.Effect = DragDropEffects.Copy;
    } else {
        e.Effect = DragDropEffects.None;
    }
}

      

+2


a source to share


2 answers


You should look into e.AllowedEffect if it DragDropEffects.Copy

is listed.

Update

A while ago I also had problems getting the correct format from GetDataPresent()

. In this regard, I just looked at the list provided GetFormats()

and did it myself. The code was something like this:



private void OnItemDragEnter(object sender, DragEventArgs e)
{
    //Get the first format out of the list and try to cast it into the
    //desired type.
    var list = e.Data.GetData(e.Data.GetFormats()[0]) as IEnumerable<ListViewItem>;
    if (list != null)
    {
        e.Effect = DragDropEffects.Copy;
    }
    else
    {
        e.Effect = DragDropEffects.None;
    }
}

      

This simple solution works for me, but you can also walk through the whole array GetFormats()

using linq and try to find the type you want IEnumerable<T>.OfType<MyType>()

or something similar.

+2


a source


If someone doesn't tell me why this is a bad idea, here's where to go with:

private void MyForm_DragEnter(object sender, DragEventArgs e) {
    e.Effect = (e.Data.GetFormats().Any(f => f == DataFormats.FileDrop)
        ? DragDropEffects.Copy
        : DragDropEffects.None);
}

      



Works from both Windows Explorer and Locate32.

0


a source







All Articles