Wednesday, September 21, 2011

Drag Drop with a Custom Icon in C#



Code:

        private void frmDragDrop_Load(object sender, EventArgs e)
        {
            //enable the dragged item to be dropped on to the target
            this.txtDropTarget.AllowDrop = true;
            //to make the custom drag icon visible over the form
            //we must allow drop on the form but take no action upon it
            this.AllowDrop = true; 
        }

        private void lblDragSource_MouseDown(object sender, MouseEventArgs e)
        {
            //initiate the drag operation
            //the given DragDropEffect iindicates cursor to use when dropping is allowed
            lblDragSource.DoDragDrop(lblDragSource.Text, DragDropEffects.Copy);
        }

        private void txtDropTarget_DragEnter(object sender, DragEventArgs e)
        {
            //if dragging has data, show the droppable cursor
            //otherwise show the no-drop cursor
            if (e.Data.GetDataPresent(DataFormats.Text))
                e.Effect = DragDropEffects.Copy;
            else
                e.Effect = DragDropEffects.None;
        }

        private void frmDragDrop_DragEnter(object sender, DragEventArgs e)
        {
            //this is where the actual "show drag icon over the form" occurs
            if (e.Data.GetDataPresent(DataFormats.Text))
                e.Effect = DragDropEffects.Copy;
            else
                e.Effect = DragDropEffects.None;
        }

        private void txtDropTarget_DragDrop(object sender, DragEventArgs e)
        {
            //process the drop action
            txtDropTarget.Text = (string)e.Data.GetData(DataFormats.Text);
        }

        private void lblDragSource_GiveFeedback(object sender, GiveFeedbackEventArgs e)
        {
            //customize the drag cursor for the given DragDropEffect for this control
            e.UseDefaultCursors = e.Effect != DragDropEffects.Copy;
            Cursor.Current = new Cursor("1.ico");
        }


Sources:
http://www.switchonthecode.com/tutorials/winforms-using-custom-cursors-with-drag-drop
http://www.switchonthecode.com/tutorials/csharp-tutorial-how-to-use-custom-cursors
http://stackoverflow.com/questions/1733912/how-do-i-handle-dragging-of-a-label-in-c