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:
- Set the AllowDrop property for the textbox to true.
- Add a DragEnter event into the textbox, storing your text.
- 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);
}
}
92c95c25-ee5c-4d49-8925-e8e6971bf206|0|.0
Tags: