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

 时间:2026-02-14 23:04:44

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

         }               

     }

      

 }

  • Postman怎么设置本地文件夹
  • IE浏览器cookie信息在哪看
  • Intellij idea 中的Darcula主题怎么把颜色改回来
  • jquery如何给div赋值
  • intellij idea如何关闭显示工具窗口栏
  • 热门搜索
    怎么解散qq群 方框里面怎么打钩 iphone怎么改字体 苹果死机怎么重启 嘴唇上火怎么办 飞鸽电动车怎么样 婴儿黄疸怎么办 声明怎么写 卖股票手续费怎么算 ppt怎么换背景