C# Drag-and-Drop: Show the dragged item while dragging

Viewed 34465

I'm building a desktop app in C# with Windows Forms. I have a custom Control, and I'd like to be able to drag and drop it within my application (not outside). Right now I'm implementing that with the usual DoDragDrop/OnDragOver/OnDragDrop methods. Is there any way to continuously paint the control as it gets dragged around--sort of what you see with JQuery's drag-and-drop? I want the actual control to stay in place, but I want to paint a copy of its appearance as the user drags it. Ideally the copy would even be semi-transparent, but that's more a "nice to have."

The only way I can think to do this is to put the paint code in the main form's OnPaint method, but that seems like an inelegant solution. Any other ideas? Are things any easier if the Control paints itself as just a Bitmap?

5 Answers

Based on a previous answer:

First define the method MouseDown (in my case i use a button, but is aplicable at other controls).

        private void btn_MouseDown(object sender, MouseEventArgs e)
    {
        //Cast the sender to control type youre using
        Button send = (Button)sender;
        //Copy the control in a bitmap
        Bitmap bmp = new Bitmap(send.Width, send.Height);
        send.DrawToBitmap(bmp, new Rectangle(Point.Empty, bmp.Size));            
        //In a variable save the cursor with the image of your controler
        this.BitMapCursor = new Cursor(bmp.GetHicon());             
        send.DoDragDrop(send.Text, DragDropEffects.Move);
    }

i am casting the sender because in my aplicattion the buttón is be generated in real time.

Now define the method GiveFeedBack(this method occurs during a drag operation.)

    private void btn_GiveFeedback(object sender, GiveFeedbackEventArgs e)
    {
        //Deactivate the default cursor
        e.UseDefaultCursors = false;       
        //Use the cursor created from the bitmap
        Cursor.Current = this.BitMapCursor;

    }

To end dont forget suscribe the control to the methods

btn.Click += new EventHandler(ClickButton);
btn.MouseDown += new MouseEventHandler(btn_MouseDown);
btn.GiveFeedback += new GiveFeedbackEventHandler(btn_GiveFeedback);
Related