摘自: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. os即时通讯客户端开发之-mac上安装MySQL

    一.安装 到MySQL官网上http://dev.mysql.com/downloads/mysql/,下载mysql可安装dmg版本 比如:Mac OS X ver. 10.7 (x86, 64-b ...

  2. duilib DirectUI库里面的一个简单的例子RichListDemo

    1.首先来看这里的CRichListWnd 已经不再是从CWindowWnd继承了 classCRichListWnd:publicWindowImplBase 从WindowImplBase中,可以 ...

  3. [Redux] Implementing Store from Scratch

    Learn how to build a reasonable approximation of the Redux Store in 20 lines. No magic! const counte ...

  4. Java基础知识强化83:System类之gc()方法(垃圾回收)以及和finalize()区别

    1. System概述: System类包含一些有用的类字段和方法.它不能被实例化. 2. gc()方法:垃圾回收器 public static void gc()       调用gc方法暗示着Ja ...

  5. 使用nice命令调整进程优先级

    Adjusting Process Priority with nice   When Linux processes are started, they are started with a spe ...

  6. linux命令chown修改文件所有权

      Changing User Ownership To apply appropriate permissions, the first thing to consider is ownership ...

  7. SQL读取系统时间的语法(转)

    --获取当前日期(如:yyyymmdd) select CONVERT (nvarchar(12),GETDATE(),112) --获取当前日期(如:yyyymmdd hh:MM:ss)select ...

  8. bootstrap字体图标

    bootstrap字体图标 http://v3.bootcss.com/components/ <!DOCTYPE HTML> <html> <head> < ...

  9. iOS9中通过UIStackView实现类似大众点评中的效果图

    效果图如下: 实现思路 整体可以看做为一个大的UIStackView(排列方式水平)包括一个子UIStackView(排列方式垂直),其中左边包括一个图片,右边的UIStackView中可以看做包括三 ...

  10. iOS-封装静态库

    最近在做Apple的IOS开发,有开发静态库的需求,本身IOS的开发,只允许静态库或者Framework.在Xcode上没有找到允许编译,如同Android上的*.so和Win32上的dll这样的说法 ...