Drag and drop files into your Windows application

by Dominic Zukiewicz 11. March 2008 15:05

Say you want to build a text editor, and want to drag files onto the program in order to open the file. Is it difficult?

NO! Its not as bad as I thought it would be anyway. Here's all you have to do:

  1. Set the AllowDrop property for the textbox to true.
  2. Add a DragEnter event into the textbox, storing your text.
  3. Add a DragDrop event into the textbox, storing your text.

In the DragEnter event, we want to change the cursor so the user knows that they are able to do this. But even before that, we have to check that the drag "type" is a file. How is that done?

private void txtWindow_DragEnter(object sender, DragEventArgs e)
{
     if (e.Data.GetDataPresent(DataFormats.FileDrop)) ;
     {
          e.Effect = DragDropEffects.Copy;
     }
}

The previous code changes the cursor to a copy cursor as defined by the OS. Next thing to do is to cater for when the mouse is released:

private void txtWindow_DragDrop(object sender, DragEventArgs e)
{
     if (e.Data.GetDataPresent(DataFormats.FileDrop)) ;
     {
          string filename = e.Data.GetData(DataFormats.FileDrop,false);
          txtWindow.Text = File.ReadAllText(filename);
     }
}

Tags:

Powered by BlogEngine.NET 1.5.0.7
Theme by Interakting

Interakting

A full service digital agency offering online strategy, design and usability, systems integration and online marketing services that deliver real business benefits and ensure your online objectives are met.

Calendar

<<  February 2012  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
2728291234
567891011

View posts in large calendar