Drag & drop in C#

There are lots of sites explaining how to do this, that’s for sure, and it ain’t difficult at all. But why not annotate it in a blog?

The goal is to have a C# application that accepts files (or folders) as input by means of drag & drop. The steps are:

1.- Set the value of the AllowDrop property to true in the control you want to serve as a drop target. (The whole form does have that property as well, if you want to receive files anywhere).

2.- Implement the DragEnter event for the control or form you’ve chosen:

if(e.Data.GetDataPresent(DataFormats.FileDrop, false) == true)
e.Effect = DragDropEffects.All;

The previous lines intend to verify that the user is dropping files, nor text or something else. But the condition is up to you; anyway, you must return a DragDropEffects constant that allows the user to drop if that’s the case.

3.- Actually accept the data (and do whatever you wanted with it) by implementing the DragDrop event on the chosen control or form. The DragEventArgs parameter is the key. This is but an example:

string[] filenames = (string[])e.Data.GetData(DataFormats.FileDrop);

The rest is up to you.



Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión / Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión / Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión / Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión / Cambiar )

Conectando a %s

A %d blogueros les gusta esto: