C # implementation file drag-and-drop (drag-and-drop)

Source: Internet
Author: User

Excerpt from: http://www.cnblogs.com/eaglet/archive/2009/01/06/1370149.html

C # WinForm The next step in implementing drag-and-drop of files

Author: eaglet

The ability to implement a similar resource browser in WinForm requires that the files listed in WinForm be dragged out into other applications or dragged into the WinForm app from other applications. There are some articles on the Internet that describe this feature, but are fragmented and lack a complete example. For this I have written a more complete example of implementing file drag-and-drop, and write this step-by-minute explanation if similar functionality is implemented.

    • Step 1 Place a ListView into the WinForm form and initialize the following properties:

Listview.view = View.Details;
Listview.allowdrop = true;

    • Step 2 compose a table of contents file List display function

/**////<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);
}
}

The code above has a section of the code to display the icon because it is irrelevant to drag, I do not post it, interested can download the full code to see.

    • Step 3 Add the DragEnter event to the ListView

The DragEnter event determines the type of object that is currently being dragged when a file is dragged into another application, and if it is a file type, set the drag response type to copy.

private void Listviewfolder_dragenter (object sender, DragEventArgs e)
{
if (E.data.getdatapresent (DataFormats.FileDrop))
{
E.effect = dragdropeffects.copy;
}
Else
{
E.effect = DragDropEffects.None;
}

}

    • Step 4 Add the DragDrop event to the ListView
The DragDrop event here completes copying the files dragged by other applications into the current directory of the WinForm app.

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);
}
}

After completing the 4 steps above, the drag-in function is implemented. The following steps complete the drag-out function

    • Step 5 Add the ItemDrag event to the ListView

This event responds when the ListView item is dragged, and we use this event to copy the file name corresponding to the currently selected item to the drag data.

And call the form's DoDragDrop method to tell the form to start the drag-and-drop operation now.

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 # implementation file drag-and-drop (drag-and-drop)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.