C# WinForm下一步一步实现文件的拖入和拖出

在WinForm实现一个类似资源浏览器的功能,需要实现将WinForm中列出的文件拖出到其他应用程序中或者从其他应用程序中将文件拖入到Winform应用中。网上有一些文章介绍这种功能,但都比较零散,缺少一个完整的例子。为此我编写了一个较完整的实现文件拖入和拖出的例子,并撰写此文一步步讲解如果实现类似功能。

步骤1 放置一个 ListView 到 Winform窗体中 并初始化如下属性:
  1.             listView.View = View.Details;
  2.             listView.AllowDrop = true;
复制代码

步骤2 撰写一个目录文件列表显示的函数
  1.         /** <summary>
  2.         /// List files in the folder
  3.         /// </summary>
  4.         /// <param name="directory">the directory of the folder</param>
  5.         private void ListFolder(string directory)
  6.         {
  7.             labelCurFolder.Text = directory;

  8.             String[] fileList = System.IO.Directory.GetFiles(directory);
  9.             listViewFolder.Items.Clear();
  10.             listViewFolder.Columns.Clear();
  11.             listViewFolder.Columns.Add("Name", 300);
  12.             listViewFolder.Columns.Add("Size", 100);
  13.             listViewFolder.Columns.Add("Time", 200);

  14.             foreach (string fileName in fileList)
  15.             {
  16.                 //Show file name
  17.                 ListViewItem itemName = new ListViewItem(System.IO.Path.GetFileName(fileName));
  18.                 itemName.Tag = fileName;

  19.                 //Show file icon

  20.                 IconImageProvider iconImageProvider = new IconImageProvider(listViewFolder.SmallImageList,

  21. listViewFolder.LargeImageList);


  22.                 itemName.ImageIndex = iconImageProvider.GetIconImageIndex(fileName);

  23.                 //Show file size
  24.                 System.IO.FileInfo fileInfo = new System.IO.FileInfo(fileName);
  25.                 long size = fileInfo.Length;

  26.                 String strSize;
  27.                 if (size < 1024)
  28.                 {
  29.                     strSize = size.ToString();
  30.                 }
  31.                 else if (size < 1024 * 1024)
  32.                 {
  33.                     strSize = String.Format("{0:###.##}KB", (float)size / 1024);
  34.                 }
  35.                 else if (size < 1024 * 1024 * 1024)
  36.                 {
  37.                     strSize = String.Format("{0:###.##}MB", (float)size / (1024 * 1024));
  38.                 }
  39.                 else
  40.                 {
  41.                     strSize = String.Format("{0:###.##}GB", (float)size / (1024 * 1024 * 1024));
  42.                 }

  43.                 ListViewItem.ListViewSubItem subItem = new ListViewItem.ListViewSubItem();
  44.                 subItem.Text = strSize;
  45.                 subItem.Tag = size;
  46.                 itemName.SubItems.Add(subItem);

  47.                 //Show file time
  48.                 subItem = new ListViewItem.ListViewSubItem();
  49.                 DateTime fileTime = System.IO.File.GetLastWriteTime(fileName);

  50.                 subItem.Text = (string)fileTime.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss"); ;
  51.                 subItem.Tag = fileTime;

  52.                 itemName.SubItems.Add(subItem);
  53.                 listViewFolder.Items.Add(itemName);
  54.             }
  55.         }
复制代码
上面代码中有一段显示图标的代码由于和拖动无关,我就不贴出来了,感兴趣可以下载完整的代码去看。

步骤3 为ListView 添加 DragEnter 事件 
  DragEnter 事件在其他应用程序拖入的文件进入时判断当前拖动的对象类型,如果是文件类型,则设置拖动响应类型为Copy.
  1.         private void listViewFolder_DragEnter(object sender, DragEventArgs e)
  2.         {
  3.             if (e.Data.GetDataPresent(DataFormats.FileDrop))
  4.             {
  5.                 e.Effect = DragDropEffects.Copy;
  6.             }
  7.             else
  8.             {
  9.                 e.Effect = DragDropEffects.None;
  10.             }

  11.         }
复制代码

步骤4 为ListView 添加 DragDrop 事件
 
DragDrop 事件在这里完成将其他应用程序拖入的文件拷贝到Winform应用当前的目录中。
  1.         private void listViewFolder_DragDrop(object sender, DragEventArgs e)
  2.         {
  3.             try
  4.             {
  5.                 String[] files = e.Data.GetData(DataFormats.FileDrop, false) as String[];

  6.                 //Copy file from external application
  7.                 foreach (string srcfile in files)
  8.                 {
  9.                     string destFile = labelCurFolder.Text + "\\" + System.IO.Path.GetFileName(srcfile);
  10.                     if (System.IO.File.Exists(destFile))
  11.                     {

  12.                         if (MessageBox.Show(string.Format(

  13. "This folder already contains a file named {0}, would you like to replace the existing file",

  14. System.IO.Path.GetFileName(srcfile)),


  15.                             "Confirm File Replace", MessageBoxButtons.YesNo, MessageBoxIcon.None) != 

  16.                               DialogResult.Yes)


  17.                         {


  18.                             continue;
  19.                         }
  20.                     }

  21.                     System.IO.File.Copy(srcfile, destFile, true);
  22.                 }

  23.                 //List current folder
  24.                 ListFolder();
  25.             }
  26.             catch (Exception e1)
  27.             {
  28.                 MessageBox.Show(e1.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
  29.             } 
  30.         }
复制代码
完成上述4步后,拖入功能就实现了。下面步骤完成拖出功能

步骤5 为ListView 添加 ItemDrag 事件 
   这个事件在ListView 的Item被拖动时响应,我们利用这个事件将当前选中的item对应的文件名复制到拖动数据中,并调用窗体的DoDragDrop方法告知窗体现在开始做拖放操作。
  1.         private void listViewFolder_ItemDrag(object sender, ItemDragEventArgs e)
  2.         {
  3.             if (e.Button == MouseButtons.Left)
  4.             {
  5.                 if (listViewFolder.SelectedItems.Count <= 0)
  6.                 {
  7.                     return;
  8.                 }

  9.                 //put selected files into a string array

  10.                 string[] files = new String[listViewFolder.SelectedItems.Count];

  11.                 int i = 0;
  12.                 foreach (ListViewItem item in listViewFolder.SelectedItems)
  13.                 {
  14.                     files[i++] = item.Tag.ToString();
  15.                 }

  16.                 //create a dataobject holding this array as a filedrop

  17.                 DataObject data = new DataObject(DataFormats.FileDrop, files);

  18.                 //also add the selection as textdata

  19.                 data.SetData(DataFormats.StringFormat, files[0]);

  20.                 //Do DragDrop
  21.                 DoDragDrop(data, DragDropEffects.Copy);
  22.             } 
  23.         }
  24.     }
复制代码
完成了步骤5,拖出功能也实现了。

完整源代码下载:
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值