如何支持在Winforms中拖放文件夹?

时间:2012-06-27 15:08:00

标签: c# winforms drag-and-drop

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

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];
    }
}

1 个答案:

答案 0 :(得分:6)

您可以测试路径是否为文件夹,并在DragEnter handler中,有条件地更改Effect

 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;
 }