c# 实现文件拖入和拖出(拖拽)
摘自:http://www.cnblogs.com/eaglet/archive/2009/01/06/1370149.html
C# WinForm下一步一步实现文件的拖入和拖出
作者:Eaglet
在WinForm实现一个类似资源浏览器的功能,需要实现将WinForm中列出的文件拖出到其他应用程序中或者从其他应用程序中将文件拖入到Winform应用中。网上有一些文章介绍这种功能,但都比较零散,缺少一个完整的例子。为此我编写了一个较完整的实现文件拖入和拖出的例子,并撰写此文一步步讲解如果实现类似功能。
- 步骤1 放置一个 ListView 到 Winform窗体中 并初始化如下属性:
listView.View = View.Details;
listView.AllowDrop = true;
- 步骤2 撰写一个目录文件列表显示的函数

/**//// <summary>
/// List files in the folder
/// </summary>
/// <param name="directory">the directory of the folder</param>
private void ListFolder(string directory)
{
labelCurFolder.Text = directory;
String[] fileList = System.IO.Directory.GetFiles(directory);
listViewFolder.Items.Clear();
listViewFolder.Columns.Clear();
listViewFolder.Columns.Add("Name", 300);
listViewFolder.Columns.Add("Size", 100);
listViewFolder.Columns.Add("Time", 200);
foreach (string fileName in fileList)
{
//Show file name
ListViewItem itemName = new ListViewItem(System.IO.Path.GetFileName(fileName));
itemName.Tag = fileName;
//Show file icon
IconImageProvider iconImageProvider = new IconImageProvider(listViewFolder.SmallImageList,
listViewFolder.LargeImageList);
itemName.ImageIndex = iconImageProvider.GetIconImageIndex(fileName);
//Show file size
System.IO.FileInfo fileInfo = new System.IO.FileInfo(fileName);
long size = fileInfo.Length;
String strSize;
if (size < 1024)
{
strSize = size.ToString();
}
else if (size < 1024 * 1024)
{
strSize = String.Format("{0:###.##}KB", (float)size / 1024);
}
else if (size < 1024 * 1024 * 1024)
{
strSize = String.Format("{0:###.##}MB", (float)size / (1024 * 1024));
}
else
{
strSize = String.Format("{0:###.##}GB", (float)size / (1024 * 1024 * 1024));
}
ListViewItem.ListViewSubItem subItem = new ListViewItem.ListViewSubItem();
subItem.Text = strSize;
subItem.Tag = size;
itemName.SubItems.Add(subItem);
//Show file time
subItem = new ListViewItem.ListViewSubItem();
DateTime fileTime = System.IO.File.GetLastWriteTime(fileName);
subItem.Text = (string)fileTime.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss"); ;
subItem.Tag = fileTime;
itemName.SubItems.Add(subItem);
listViewFolder.Items.Add(itemName);
}
}
上面代码中有一段显示图标的代码由于和拖动无关,我就不贴出来了,感兴趣可以下载完整的代码去看。
- 步骤3 为ListView 添加 DragEnter 事件
DragEnter 事件在其他应用程序拖入的文件进入时判断当前拖动的对象类型,如果是文件类型,则设置拖动响应类型为Copy.
private void listViewFolder_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
- 步骤4 为ListView 添加 DragDrop 事件
DragDrop 事件在这里完成将其他应用程序拖入的文件拷贝到Winform应用当前的目录中。
private void listViewFolder_DragDrop(object sender, DragEventArgs e)
{
try
{
String[] files = e.Data.GetData(DataFormats.FileDrop, false) as String[];
//Copy file from external application
foreach (string srcfile in files)
{
string destFile = labelCurFolder.Text + "\\" + System.IO.Path.GetFileName(srcfile);
if (System.IO.File.Exists(destFile))
{
if (MessageBox.Show(string.Format(
"This folder already contains a file named {0}, would you like to replace the existing file",
System.IO.Path.GetFileName(srcfile)),
"Confirm File Replace", MessageBoxButtons.YesNo, MessageBoxIcon.None) !=
DialogResult.Yes)

{
continue;
}
}
System.IO.File.Copy(srcfile, destFile, true);
}
//List current folder
ListFolder();
}
catch (Exception e1)
{
MessageBox.Show(e1.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
完成上述4步后,拖入功能就实现了。下面步骤完成拖出功能
- 步骤5 为ListView 添加 ItemDrag 事件
这个事件在ListView 的Item被拖动时响应,我们利用这个事件将当前选中的item对应的文件名复制到拖动数据中,
并调用窗体的DoDragDrop方法告知窗体现在开始做拖放操作。
private void listViewFolder_ItemDrag(object sender, ItemDragEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
if (listViewFolder.SelectedItems.Count <= 0)
{
return;
}
//put selected files into a string array
string[] files = new String[listViewFolder.SelectedItems.Count];
int i = 0;
foreach (ListViewItem item in listViewFolder.SelectedItems)
{
files[i++] = item.Tag.ToString();
}
//create a dataobject holding this array as a filedrop
DataObject data = new DataObject(DataFormats.FileDrop, files);
//also add the selection as textdata
data.SetData(DataFormats.StringFormat, files[0]);
//Do DragDrop
DoDragDrop(data, DragDropEffects.Copy);
}
}
}

c# 实现文件拖入和拖出(拖拽)的更多相关文章
- unity 3D Mesh网络模型,怎样将Constructer拖入场景??
下图中的将Constructer拖入场景,怎么拖入,不知道... 1.Constructer是一个什么东西?在 下图中没有看到这个名字的,于是乎,我就不知道该怎么办了...
- 拖入浏览器读取文件demo
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- VMware Tools安装,设置centos全屏、可拖入文件功能
Mr·Hu原创作品.转载请注明出处http://www.cnblogs.com/huxiuqian/p/7843126.html 由于在VM中使用小屏太不方便,所以进行全屏化,亦可进行文件共享. 1. ...
- 解决SecureCRT远程Linux遇到文件不能直接往CRT里直接拖入的问题
不能拖入到CRT的第一个原因可能是Options-->Global Options-->Terminal中的Mouse下的Copy on select没有勾选.当发现自己勾选了也不能往里面 ...
- Xcode中将图片放入Images.xcassets和直接拖入的区别
将图片放入Images.xcassets 在mainBundle里面Xcode会生成一个Assets.car文件,将我们放在Images.xcassets的图片打包在里面.(程序会变大(?)) 无论是 ...
- mac github工具将命令当下来的代码拖入macgithub中就可以
mac github工具将命令当下来的代码拖入macgithub中就可以,刚開始傻傻的就知道点击那个加入button,总是在当下来的文件夹下创建个文件夹.并且代码不能同步
- firebug离线安装方法-拖入法
这里介绍的是如何在Firefox中离线安装firebug插件. 1, 下载firebug离线包, 一般就是一个*.xpi文件; 2, 打开Firefox浏览器,直接将*.xpi文件拖入Firefox浏 ...
- Mac将应用拖入Finder工具栏
在Finder的工具栏上放一下应用,方便打开对应的文件,可以 Command + 鼠标拖动应用,将应用拖入Finder工具栏中. 本人的Finder工具栏上添加了vscode这个应用
- 在Winform框架的多文档界面中实现双击子窗口单独弹出或拖出及拽回的处理
在基于DevExpress的多文档窗口界面中,我们一般使用XtraTabbedMdiManager来管理多文档窗口的一些特性,如顶部菜单,页面的关闭按钮处理,以及一些特殊的设置,本篇随笔介绍这些特点, ...
随机推荐
- Opencv学习笔记(六)SURF学习笔记
原创文章,转载请注明出处:http://blog.csdn.net/crzy_sparrow/article/details/7392345 本人挺菜的,肯定有非常多错误纰漏之处 ,希望大家不吝指正. ...
- Neutron中的Service类
Service是OpenStack中非常重要的一个概念,各个服务的组件都以Service类的方式来进行交互. Neutron中的Service类继承自rpc中的Service,总体的继承关系为 neu ...
- HTTPS 详解
1) HTTPS是什么 https 是超文本传输安全协议的缩写.HTTPS主要思想是在不安全的网络上创建一种安全的信道,并且可以在使用适当的加密包和服务器证书可被验证且可被信任时候,对窃听和中间人攻击 ...
- JAVA 多线程同步与互斥
1. 为什么需要互斥: 互斥操作 保证了 多线程操作的 原子性 , java的 互斥 语义 有 synchronized 关键字 提供. 主要方式 有 同步代码块 和 同步方法 两种 2. ...
- Vim的多窗口模式管理
Vim中的多窗口打开 vim中,默认的多窗口打开,是横向分割窗口. 进入vim编辑器以后,可以通过new命令,新建一个子窗口 :new “新建一个未命名窗口 :new name "新建一个 ...
- divmod(a,b)函数
python每日一函数 - divmod数字处理函数 divmod(a,b)函数 中文说明: divmod(a,b)方法返回的是a//b(除法取整)以及a对b的余数 返回结果类型为tuple 参数: ...
- 一个控制台贪吃蛇小游戏(wsad控制移动)
/******************************************** * 程序名称:MR.DUAN 的贪吃蛇游戏(链表法) * 作 者:WindAutumn <flutti ...
- Assembly 'Microsoft.Office.Interop.Excel
编译的时候报错,都无法通过编译: Assembly 'Microsoft.Office.Interop.Excel, Version=14.0.0.0, Culture=neutral, Public ...
- PHP 类型比较表
以下的表格显示了 PHP 类型和比较运算符在松散和严格比较时的作用.该补充材料还和类型戏法的相关章节内容有关.同时,大量的用户注释和 » BlueShoes 的工作也给该材料提供了帮助. 在使用这些表 ...
- LINQ对List列表随机排序,取N条数据
List<Art_Search> artList=new List<Art_Search>(); artList=artList.OrderBy(s => Guid.Ne ...