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

ε祈祈猫儿з 提交于 2019-12-11 01:26:45

问题


I'm trying to drag files into my application from a program called Locate32 (which is great by the way). Here is what happens:

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 e.Data.GetDataPresent(DataFormats.FileDrop) return false even though FileDrop is clearly one of the formats listed as "available"?

If I do e.Data.GetData(DataFormats.FileDrop) I get a list of a bunch of filenames, as I should. Also, drag and drop works fine from Windows Explorer.

Here's 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;
    }
}

回答1:


You should take a look into e.AllowedEffect if DragDropEffects.Copy is within the list.

Update

Some time ago i also had some problems with getting the right format out of the GetDataPresent(). Due to this fact, i just looked directly into the list provided by GetFormats() and did it on myself. The code was something like that:

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 could also walk all over the GetFormats() array with linq and try to find your desired type by IEnumerable<T>.OfType<MyType>() or something similar.




回答2:


Unless someone can tell me why this is a bad idea, here's what I'm going 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.



来源:https://stackoverflow.com/questions/2850870/e-data-getdatapresent-not-working-in-winforms-drag-and-drop-handler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!