C#中让ListBox支持文件路径的拖放DragDrop
有时,我们程序,需要加载一个文件列表,这个列表,通常用 ListBox 来存放,为了方便操作,让listBox支持拖放入文件的路径,是个非常好的功能,在 .NET 里面实现这个功能,是非常方便和容易的,只需要3个步骤:
- 将 ListBox 的 AllowDrop 属性设为 true
- 在 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); } }
这样就搞定了,哈哈
是不是灰常容易呢
作者: 三角猫
http://www.zu14.cn/
转载请保留此信息