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

PS:最近在整理浏览器收藏夹中以前收藏的一些文章,把自己以前用到的或者感觉以后会用到的都转帖一下,勿拍砖。

本文通过五个步骤详细介绍C# 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 事件
private void listViewFolder_DragEnter(object sender, DragEventArgs e)
{
    if (e.Data.GetDataPresent(DataFormats.FileDrop))
    {
        e.Effect = DragDropEffects.Copy;
    }
    else
    {
        e.Effect = DragDropEffects.None;
    }
}
DragEnter 事件在其他应用程序拖入的文件进入时判断当前拖动的对象类型,如果是文件类型,则设置拖动响应类型为Copy。


步骤4、为ListView 添加 DragDrop 事件 
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);
    }
}
DragDrop 事件在这里完成将其他应用程序拖入的文件拷贝到Winform应用当前的目录中。
完成上述4步后,拖入功能就实现了,下面步骤完成拖出功能。


步骤5、为ListView 添加 ItemDrag 事件 
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);
    }
}

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


From: http://dotnet.9sssd.com/winform/art/12


  • 2
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值