关于c#:我如何支持在Winforms中拖放文件夹?

How do I support dragging and dropping a folder in Winforms?

我想知道如何拖放文件夹并获取其名称。我已经知道如何处理一个文件,但我不确定如何修改它,以便能够拖动文件夹。以下是删除文件时触发的事件代码:

1
2
3
4
5
6
7
8
9
private void checkedListBox_DragDrop(object sender, DragEventArgs e)
{
    if (e.Data.GetDataPresent(DataFormats.FileDrop))
    {
        // NB: I'm only interested in the first file, even if there were
        // multiple files dropped
        string fileName = ((string[])e.Data.GetData(DataFormats.FileDrop))[0];
    }
}


您可以测试路径是否为文件夹,并且在您的DragEnter处理程序中,有条件地更改Effect

1
2
3
4
5
6
7
8
9
10
11
12
 void Target_DragEnter(object sender, DragEventArgs e)
 {
     DragDropEffects effects = DragDropEffects.None;
     if (e.Data.GetDataPresent(DataFormats.FileDrop))
     {
         var path = ((string[])e.Data.GetData(DataFormats.FileDrop))[0];
         if (Directory.Exists(path))
             effects = DragDropEffects.Copy;
     }

     e.Effect = effects;
 }