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

Tun*_*uni 1 c# drag-and-drop winforms

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

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];
    }
}
Run Code Online (Sandbox Code Playgroud)

use*_*116 6

您可以测试路径是否是文件夹,并在DragEnter处理程序中有条件地更改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;
 }
Run Code Online (Sandbox Code Playgroud)