摘自: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# 实现文件拖入和拖出(拖拽)的更多相关文章

  1. unity 3D Mesh网络模型,怎样将Constructer拖入场景??

    下图中的将Constructer拖入场景,怎么拖入,不知道... 1.Constructer是一个什么东西?在 下图中没有看到这个名字的,于是乎,我就不知道该怎么办了...

  2. 拖入浏览器读取文件demo

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  3. VMware Tools安装,设置centos全屏、可拖入文件功能

    Mr·Hu原创作品.转载请注明出处http://www.cnblogs.com/huxiuqian/p/7843126.html 由于在VM中使用小屏太不方便,所以进行全屏化,亦可进行文件共享. 1. ...

  4. 解决SecureCRT远程Linux遇到文件不能直接往CRT里直接拖入的问题

    不能拖入到CRT的第一个原因可能是Options-->Global Options-->Terminal中的Mouse下的Copy on select没有勾选.当发现自己勾选了也不能往里面 ...

  5. Xcode中将图片放入Images.xcassets和直接拖入的区别

    将图片放入Images.xcassets 在mainBundle里面Xcode会生成一个Assets.car文件,将我们放在Images.xcassets的图片打包在里面.(程序会变大(?)) 无论是 ...

  6. mac github工具将命令当下来的代码拖入macgithub中就可以

    mac github工具将命令当下来的代码拖入macgithub中就可以,刚開始傻傻的就知道点击那个加入button,总是在当下来的文件夹下创建个文件夹.并且代码不能同步

  7. firebug离线安装方法-拖入法

    这里介绍的是如何在Firefox中离线安装firebug插件. 1, 下载firebug离线包, 一般就是一个*.xpi文件; 2, 打开Firefox浏览器,直接将*.xpi文件拖入Firefox浏 ...

  8. Mac将应用拖入Finder工具栏

    在Finder的工具栏上放一下应用,方便打开对应的文件,可以 Command + 鼠标拖动应用,将应用拖入Finder工具栏中. 本人的Finder工具栏上添加了vscode这个应用

  9. 在Winform框架的多文档界面中实现双击子窗口单独弹出或拖出及拽回的处理

    在基于DevExpress的多文档窗口界面中,我们一般使用XtraTabbedMdiManager来管理多文档窗口的一些特性,如顶部菜单,页面的关闭按钮处理,以及一些特殊的设置,本篇随笔介绍这些特点, ...

随机推荐

  1. 你需要知道的九大排序算法【Python实现】之插入排序

    三.插入排序 基本思想:插入排序的基本操作就是将一个数据插入到已经排好序的有序数据中,从而得到一个新的.个数加一的有序数据,算法适用于少量数据的排序,时间复杂度为O(n^2).是稳定的排序方法.插入算 ...

  2. [Falcor] Intro to JSON Graph

    JSON is a very commonly used data interchange format. Unfortunately while most application domain mo ...

  3. RSA加密解密及数字签名Java实现--转

    RSA公钥加密算法是1977年由罗纳德·李维斯特(Ron Rivest).阿迪·萨莫尔(Adi Shamir)和伦纳德·阿德曼(Leonard Adleman)一起提出的.当时他们三人都在麻省理工学院 ...

  4. JavaScript 总结

    1. JavaScript prototype属性是一个对象 当一个函数在定义之后 就会自动获得这个属性.其初始值是一个空对象.新建了一个名为Cat的构造函数,其prototype为一个对象,cons ...

  5. C++输出hello world 详细注释

    /* #include<iostream> #:预处理标志,后面跟预处理指令,include:预处理指令,包含 <iostream>:c++头文件,输入输出流 这行的作用就是在 ...

  6. c#将Excel数据导入到数据库的实现代码(转载)

    假如Excel中的数据如下:     数据库建表如下:     其中Id为自增字段:      代码如下: using System; using System.Collections.Generic ...

  7. HTML基础总结<段落>

    HTML 段落 段落是通过 <p> 标签定义的. 实例 <p>This is a paragraph </p><p>This is another pa ...

  8. asp.net 定时器

    using System;using System.Collections.Generic;using System.Web;using System.IO;using System.Web.Secu ...

  9. raw和字符串的转换。

    hextoraw():十六进制字符串转换为raw: rawtohex():将raw串转换为十六进制: select hextoraw('gggggg') from dual

  10. PHP 运算符

    本章节我们将讨论 PHP 中不同运算符的应用. 在 PHP 中,赋值运算符 = 用于给变量赋值. 在 PHP 中,算术运算符 + 用于把值加在一起. PHP 算术运算符 运算符 名称 描述 实例 结果 ...