Handling Drag and Drop Events

The following code shows you how Drag and Drop is implemented in this sample program and in the Text Control Words demo application. It allows files to be dropped on all parts of the application, including the text area. The code has been encapsulated in a class named DragDropHandler for easy re-use in your programs.

First, you need to instantiate the class:

[C#]
FileDragDropHandler fileDragDrop = new FileDragDropHandler();
[Visual Basic]
Dim FileDragDrop As New FileDragDropHandler

After that, you can use the form's and the control's events to handle files that will be dropped on the form or control. These are the TX Text Control events which have to be handled with the help of the DragDropHandler class. The form's events are handled the same way.

[C#]
private void textControl1_DragDrop(object sender, DragEventArgs e)
{
  loadFile(fileDragDrop.FileName, fileDragDrop.StreamType);
}

private void textControl1_DragEnter(object sender, DragEventArgs e)
{
  fileDragDrop.Reset();
  fileDragDrop.CheckDraggedFiles((string[])e.Data.GetData(DataFormats.FileDrop));
}

private void textControl1_DragOver(object sender, DragEventArgs e)
{
  if (fileDragDrop.CanDrop == true)
    e.Effect = fileDragDrop.GetDragDropEffect(e.AllowedEffect, e.KeyState);
}
[Visual Basic]
Private Sub TextControl1_DragDrop(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DragEventArgs) _
Handles TextControl1.DragDrop
  LoadFile(FileDragDrop.FileName, FileDragDrop.StreamType)
End Sub

Private Sub TextControl1_DragEnter(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DragEventArgs) _
Handles TextControl1.DragEnter
  FileDragDrop.Reset()
  FileDragDrop.CheckDraggedFiles(CType(e.Data.GetData(DataFormats.FileDrop), String()))
End Sub

Private Sub TextControl1_DragOver(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DragEventArgs) _
Handles TextControl1.DragOver
  If FileDragDrop.CanDrop = True Then
    e.Effect = FileDragDrop.GetDragDropEffect(e.AllowedEffect, e.KeyState)
  End If
End Sub

In the DragEnter event, the file extension will be checked against the supported file types.

If the dragged file is supported, the CanDrop property returns true, which can be used to decide if the DragDrop will be allowed. As you can see, the GetDragDropEffect function returns a DragDropEffects type value based on the current Keystate, which can easily be used to control the desired cursor.

Finally, the DragDrop event is fired and the dropped file is loaded.

<< Previous