Dragging and dropping onto a RichTextBox

One of many flaws with the RichTextBox control is its lack of support for drag/drop operations. Luckily it’s simple to add. In fact, it’s so simple you’ll wonder why they didn’t just support it out of the box.

Let’s assume that you’ve created a form and added a RichTextBox called richTextBox1. Rather then going to the properties window to add the events, you’ll need to do it yourself.

Add the following in the constructor of the form:

richTextBox1.AllowDrop = true;
richTextBox1.DragDrop += new DragEventHandler(richTextBox1_DragDrop);
richTextBox1.DragEnter += new DragEventHandler(richTextBox1_DragEnter);

Type in the “+=” and press tab to automatically complete the line, then press tab again to create the function. Or just add the handler functions manually:

public void richTextBox1_DragEnter(object sender, DragEventArgs e) {
	if (e.Data.GetDataPresent(DataFormats.FileDrop)) {
		e.Effect = DragDropEffects.Copy;
	}
	else {
		e.Effect = DragDropEffects.None;
	}
}

public void richTextBox1_DragDrop(object sender, DragEventArgs e) {
	string[] filenames = (string[])e.Data.GetData(DataFormats.FileDrop);

	foreach (string filename in filenames) {
		// code to process a filename
	}
}

You can also implement DragOver and DragLeave in the same way, although those are there to “support the .NET Framework infrastructure” and are “not intended to be used directly from your code”. Intellisense doesn’t even show those events, but you can type them in and compile without problems. Also note that DragLeave is an EventHandler rather then a DragEventHandler.

Creative Commons License
This work, unless otherwise expressly stated, is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 License.
This entry was posted in .net, C#, Programming and tagged , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>