C#/VB.NET实现拖拽添加文件/文件夹并获得路径

2025-09-28 11:43:47

1、首先,

在窗体上添加一个ListBox控件,将其AllowDrop属性设置为True。

2、接着,

在该控件的DragEnter事件添加如下代码:

private void lsFiles_DragEnter(object sender, DragEventArgs e)

{

    if (e.Data.GetDataPresent(DataFormats.FileDrop))

    {

        e.Effect = DragDropEffects.Link;

    }

    else

    {

        e.Effect = DragDropEffects.None;

    }

}

需要注意的是,这个事件的代码不得不写,否则会失效。

3、然后,

在该控件的DragDrop事件添加如下代码:

private void lsReady_DragDrop(object sender, DragEventArgs e)

{

    foreach (string filepath in (System.Array)e.Data.GetData(DataFormats.FileDrop))

    {

        lsFiles.Items.Add(filepath);

    }

     

}

4、最后,

运行该程序,可以发现直接向该list拖入文件或文件夹,即可添加到它的项目列表。

5、如果只想保留文件,不想保留文件夹,可以改成如下代码:

private void lsReady_DragDrop(object sender, DragEventArgs e)

 {

     foreach (string filepath in (System.Array)e.Data.GetData(DataFormats.FileDrop))

     {

         if (File.Exists(filepath))

         {

             lsFiles.Items.Add(filepath);

         }               

     }

      

 }

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢