Desktop Drag & Drop

How to use drag & drop in your desktop apps . What this app will do is allow you to drag picture files from the Finder onto a Canvas to display and then drag the image from the Canvas out to another app.

So to start, since we’re accepting files, I’m going to add some file types to the project. So I’ll add a File Type Set and then here. I’m going to choose JPEG files and then also allow PNG files. On the window it’s just going to be a big Canvas. We are only interested in things that are going to be dragged onto the Window and since we’re dealing with graphics we going to do it right in the Canvas. So we are going to make a big Canvas here on the window.

It takes up most of the area. And then I’m going to add some events to the Canvas. And there’s several events we need to handle all this. You can see the full event list here for the Canvas. The first thing we need is the DropObject event, that’s called when something gets dropped onto the Canvas.

The MouseDown and MouseDrag are the next ones we want and that will enable you dragging something out of the Canvas. The Open event will be used to set the Canvas up and then the Paint event will be used to actually draw the image in the Canvas So starting with the Open event, here I’m going to put in some code that will say what type of things we can accept [as a drag]. So we will accept a regular picture and then we’ll also accept files.

In this case the PNG and JPEG files that we added to the File Types In the DropObject event we can check the Object parameter (obj parameter) and check what type of thing was dropped. So if it was an actual picture or if it’s a file then we’ll open the file and save the picture And both of those are being saved to a property of the window. In the Paint event we check if the property has a value and then we draw it.

But of course, I didn’t actually create the property yet so we’re gonna get a compile error. So now I can add the property. And then I’ll run the project. You’ll just get a blank window here From the Finder, I’m gonna select a graphic file (a PNG) and just drag it in there and you see it displays.

So the next thing to do is allow you to take that picture that you dragged into the Canvas and drag it out into another app. So we’ll “Return True” in MouseDown. That just allows the MouseDrag event to get called And that’s where we really want our code. And in the MouseDrag event I create a new small version of the image that was dragged in to the Canvas.

And then I create a DragItem using that small image and then I start the drag by calling the Drag method. This will allow you to click in the Canvas and drag the picture. So we run this project now and I will add another file in here. So we’ll put that picture in there and I started the Acorn graphics drawing tool and I can just drag the picture right from the app.

And that’s how you use drag & drop in your desktop apps