摘自: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. Drupal 实战

    <Drupal 实战> 基本信息 作者: 葛红儒    丛书名: 实战系列 出版社:机械工业出版社 ISBN:9787111429999 上架时间:2013-6-28 出版日期:2013 ...

  2. 27个Jupyter快捷键、技巧(原英文版)

    本文是转发自:https://www.dataquest.io/blog/jupyter-notebook-tips-tricks-shortcuts/ 的一篇文章,先记录在此,等有空时我会翻译成中文 ...

  3. Install the OpenStack command-line

    Install the OpenStack command-line Install the prerequisite software python 2.7 or later note: Curre ...

  4. css的clip裁剪

    clip 属性是用来设置元素的形状.用来剪裁绝对定位元素(absolute or fixed). clip有三种取值:auto |inherit|rect.inherit是继承,ie不支持这个属性, ...

  5. HTML中属性ID和属性NAME的区别(转)

    ID和Name都可以用来标识一个标记,Javascript分别有两个方法getElementById和getElementByName来定位Dom节点. 区别如下: 1.我们知道在网页做Post提交时 ...

  6. shell 中 2>&1 的使用

    一 相关知识 1)默认地,标准的输入为键盘,但是也可以来自文件或管道(pipe |). 2)默认地,标准的输出为终端(terminal),但是也可以重定向到文件,管道或后引号(backquotes ` ...

  7. PHP Cookies

    PHP Cookies cookie 常用于识别用户. Cookie 是什么? cookie 常用于识别用户.cookie 是一种服务器留在用户计算机上的小文件.每当同一台计算机通过浏览器请求页面时, ...

  8. php插入转义与查找转义

    //转义用于查找 function deepslashes($data) { //判断data表现形式 if(empty($data)) { return $data; } return is_arr ...

  9. C++拾遗(四)指针相关

    指针声明与初始化 在将指针初始化为一个确定的地址后,才能安全的对指针使用 *操作. 将整数赋值给指针时要使用强制转换(typeName *). 分配内存 C中用malloc(); C++更提倡使用ne ...

  10. java动态缓存技术:WEB缓存应用(转)

    可以实现不等待,线程自动更新缓存 Java动态缓存jar包请下载. 源代码: CacheData.java 存放缓存数据的Bean /** *  */package com.cari.web.cach ...