C#中让ListBox支持文件路径的拖放DragDrop

有时,我们程序,需要加载一个文件列表,这个列表,通常用 ListBox 来存放,为了方便操作,让listBox支持拖放入文件的路径,是个非常好的功能,在 .NET 里面实现这个功能,是非常方便和容易的,只需要3个步骤:

  1. 将 ListBox 的 AllowDrop 属性设为 true
  2. 在 ListBox 的 DragOver 和 DragEnter 事件中处理
void ListBox1DragEnter(object sender, DragEventArgs e)
{
    e.Effect = DragDropEffects.All;
}

void ListBox1DragOver(object sender, DragEventArgs e)
{
    e.Effect = DragDropEffects.All;
}
    

上面的 e.Effect 可以根据实际情况,调节不同的值,不过,如果不确定,就用默认的All

   3. 处理拖放事件

void ListBox1DragDrop(object sender, DragEventArgs e)
{
    if (e.Data.GetDataPresent(DataFormats.FileDrop, false))
    {
        String[] files = (String[])e.Data.GetData(DataFormats.FileDrop);
        foreach (String s in files)
        {
            (sender as ListBox).Items.Add(s);
        }
    }
    

这样就搞定了,哈哈

是不是灰常容易呢

posted @ 2009-03-13 08:29  三角猫  阅读(516)  评论(1编辑  收藏  举报