You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中实现文件拖入ListBox并获取文件路径?

实现Windows Forms ListBox拖拽文件显示路径

步骤1:开启ListBox的拖拽允许

先确保你的ListBox允许接收拖拽内容,有两种方式:

  • 设计器设置:选中listBox1,在属性面板找到AllowDrop,设置为True
  • 代码设置:在窗体构造函数中添加:
public YourFormName()
{
    InitializeComponent();
    listBox1.AllowDrop = true;
}

步骤2:实现DragEnter事件

这个事件用来判断拖拽的内容是否是文件,设置允许的拖拽效果:

private void listBox1_DragEnter(object sender, DragEventArgs e)
{
    // 验证拖拽数据是否为文件路径格式
    if (e.Data.GetDataPresent(DataFormats.FileDrop))
    {
        e.Effect = DragDropEffects.Copy; // 允许复制式拖拽
    }
    else
    {
        e.Effect = DragDropEffects.None; // 拒绝非文件的拖拽
    }
}

步骤3:实现DragDrop事件

这个事件处理实际的拖拽操作,将文件路径添加到ListBox:

private void listBox1_DragDrop(object sender, DragEventArgs e)
{
    // 提取拖拽的所有文件路径
    string[] filePaths = (string[])e.Data.GetData(DataFormats.FileDrop);
    
    // 遍历路径并添加到ListBox(可添加重复判断避免重复项)
    foreach (string path in filePaths)
    {
        // 可选:避免重复添加
        if (!listBox1.Items.Contains(path))
        {
            listBox1.Items.Add(path);
        }
    }
}

绑定事件(如果设计器没自动绑定)

如果是手动写的事件方法,需要在构造函数中绑定事件:

public YourFormName()
{
    InitializeComponent();
    listBox1.AllowDrop = true;
    // 绑定事件
    listBox1.DragEnter += listBox1_DragEnter;
    listBox1.DragDrop += listBox1_DragDrop;
}

操作完成后,你就可以把本地文件直接拖到listBox1中,文件路径会逐个显示在列表里。

内容的提问来源于stack exchange,提问作者TheLooser2

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 16:40:34