C# WinForm 实现文件的拖入和拖出(拖拽操作)

来源:互联网 发布:怎么卸载手机管家软件 编辑:程序博客网 时间:2024/06/06 03:56

本文通过五个步骤详细介绍C# WinForm 实现文件的拖入和拖出(拖拽操作),每个步骤都提供相关的示例代码供参考。

步骤1、放置一个 ListView 到 Winform窗体中 并初始化如下属性:
[csharp] view plain copy
  1. listView.View = View.Details;   
  2. listView.AllowDrop = true;  

步骤2、撰写一个目录文件列表显示的函数 
[csharp] view plain copy
  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.    
  9.     String[] fileList = System.IO.Directory.GetFiles(directory);  
  10.     listViewFolder.Items.Clear();  
  11.     listViewFolder.Columns.Clear();  
  12.     listViewFolder.Columns.Add(" Name ", 300);  
  13.     listViewFolder.Columns.Add(" Size ", 100);  
  14.     listViewFolder.Columns.Add(" Time ", 200);  
  15.    
  16.     foreach (string fileName in fileList)  
  17.     {  
  18.         // Show file name   
  19.         ListViewItem itemName = new ListViewItem(System.IO.Path.GetFileName(fileName));  
  20.         itemName.Tag = fileName;  
  21.    
  22.         // Show file icon  
  23.    
  24.         IconImageProvider iconImageProvider = new IconImageProvider(listViewFolder.SmallImageList, listViewFolder.LargeImageList);  
  25.    
  26.         itemName.ImageIndex = iconImageProvider.GetIconImageIndex(fileName);  
  27.    
  28.         // Show file size   
  29.         System.IO.FileInfo fileInfo = new System.IO.FileInfo(fileName);  
  30.         long size = fileInfo.Length;  
  31.    
  32.         String strSize;  
  33.         if (size < 1024)  
  34.         {  
  35.             strSize = size.ToString();  
  36.         }  
  37.         else if (size < 1024 * 1024)  
  38.         {  
  39.             strSize = String.Format(" {0:###.##}KB ", (float)size / 1024);  
  40.         }  
  41.         else if (size < 1024 * 1024 * 1024)  
  42.         {  
  43.             strSize = String.Format(" {0:###.##}MB ", (float)size / (1024 * 1024));  
  44.         }  
  45.         else  
  46.         {  
  47.             strSize = String.Format(" {0:###.##}GB ", (float)size / (1024 * 1024 * 1024));  
  48.         }  
  49.    
  50.         ListViewItem.ListViewSubItem subItem = new ListViewItem.ListViewSubItem();  
  51.         subItem.Text = strSize;  
  52.         subItem.Tag = size;  
  53.         itemName.SubItems.Add(subItem);  
  54.    
  55.         // Show file time   
  56.         subItem = new ListViewItem.ListViewSubItem();  
  57.         DateTime fileTime = System.IO.File.GetLastWriteTime(fileName);  
  58.    
  59.         subItem.Text = (string)fileTime.ToLocalTime().ToString(" yyyy-MM-dd HH:mm:ss "); ;  
  60.         subItem.Tag = fileTime;  
  61.    
  62.         itemName.SubItems.Add(subItem);  
  63.         listViewFolder.Items.Add(itemName);  
  64.     }  
  65. }  
上面代码中有一段显示图标的代码由于和拖动无关,我就不贴出来了,感兴趣可以下载完整的代码去看。


步骤3、为ListView 添加 DragEnter 事件
[csharp] view plain 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. }  
DragEnter 事件在其他应用程序拖入的文件进入时判断当前拖动的对象类型,如果是文件类型,则设置拖动响应类型为Copy。


步骤4、为ListView 添加 DragDrop 事件 
[csharp] view plain copy
  1. private void listViewFolder_DragDrop(object sender, DragEventArgs e)  
  2. {  
  3.     try  
  4.     {  
  5.         String[] files = e.Data.GetData(DataFormats.FileDrop, falseas String[];  
  6.    
  7.         // Copy file from external application   
  8.         foreach (string srcfile in files)  
  9.         {  
  10.             string destFile = labelCurFolder.Text + " \\ " + System.IO.Path.GetFileName(srcfile);  
  11.             if (System.IO.File.Exists(destFile))  
  12.             {  
  13.                 if (MessageBox.Show(string.Format(  
  14.                 " This folder already contains a file named {0}," +  
  15.                 "would you like to replace the existing file ",  
  16.                 System.IO.Path.GetFileName(srcfile)),  
  17.                 " Confirm File Replace ",  
  18.                 MessageBoxButtons.YesNo,  
  19.                 MessageBoxIcon.None) != DialogResult.Yes)  
  20.                 {  
  21.                     continue;  
  22.                 }  
  23.             }  
  24.    
  25.             System.IO.File.Copy(srcfile, destFile, true);  
  26.         }  
  27.    
  28.         // List current folder   
  29.         ListFolder();  
  30.     }  
  31.     catch (Exception e1)  
  32.     {  
  33.         MessageBox.Show(e1.Message, " Error ",  
  34.         MessageBoxButtons.OK, MessageBoxIcon.Error);  
  35.     }  
  36. }  
DragDrop 事件在这里完成将其他应用程序拖入的文件拷贝到Winform应用当前的目录中。
完成上述4步后,拖入功能就实现了,下面步骤完成拖出功能。


步骤5、为ListView 添加 ItemDrag 事件 
[csharp] view plain copy
  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.    
  10.         // put selected files into a string array  
  11.         string[] files = new String[listViewFolder.SelectedItems.Count];  
  12.    
  13.         int i = 0;  
  14.         foreach (ListViewItem item in listViewFolder.SelectedItems)  
  15.         {  
  16.             files[i++] = item.Tag.ToString();  
  17.         }  
  18.    
  19.         // create a dataobject holding this array as a filedrop  
  20.         DataObject data = new DataObject(DataFormats.FileDrop, files);  
  21.    
  22.         // also add the selection as textdata  
  23.         data.SetData(DataFormats.StringFormat, files[0]);  
  24.    
  25.         // Do DragDrop   
  26.         DoDragDrop(data, DragDropEffects.Copy);  
  27.     }  
  28. }  

   这个事件在ListView 的Item被拖动时响应,我们利用这个事件将当前选中的item对应的文件名复制到拖动数据中,并调用窗体的DoDragDrop方法告知窗体现在开始做拖放操作。
通过以上5个步骤,C# WinForm程序的文件拖拽操作功能就可以实现了。
阅读全文
0 0
原创粉丝点击