简体   繁体   中英

Drag And Drop on Customized Control C#

I created a control (called Table) made up by two pictureBoxes and two Labels.

I'm trying to drag and drop it from a panel to another, but it doesn't work. This is my code:

    void TableExampleMouseDown(object sender, MouseEventArgs e)
    {
        tableExample.DoDragDrop(tableExample, DragDropEffects.Copy);
    }

    void Panel2DragEnter(object sender, DragEventArgs e)
    {
        e.Effect = DragDropEffects.Copy;
    }

    void Panel2DragDrop(object sender, DragEventArgs e)
    {
        panel2.Controls.Add((Table) e.Data.GetData(e.Data.GetFormats()[0]));
    }

Obviously I've set AllowDrop to true in panel2. Already when I click on Table object (which is in panel1), the mouse cursor doesn't change. It looks like the MouseDown event doesn't fire...

Thank you!

This is the part of the constructor code in which I subscribe Handlers:

        this.tableExample.MouseDown += new System.Windows.Forms.MouseEventHandler(this.TableExampleMouseDown);
        this.label2.MouseDown += new System.Windows.Forms.MouseEventHandler(this.Label2MouseDown);
        this.panel1.DragDrop += new System.Windows.Forms.DragEventHandler(this.Panel1DragDrop);
        this.panel1.DragEnter += new System.Windows.Forms.DragEventHandler(this.Panel1DragEnter);

You seem to have forgot to subscribe to the MouseDown event. Simply writing an event hanlder isn't enough.

Put this in the Form_Load event handler or in the form's constructor:

tableExample.MouseDown += new MouseEventHandler(TableExampleMouseDown);

For more information refer to the documentation: How to: Subscribe to and Unsubscribe from Events - Microsoft Docs .


EDIT:

It could also be that you press one of the child controls of your custom control. Child controls have their own MouseDown events.

To make the child controls also raise the parent control's MouseDown event put this in the constructor of your custom control :

MouseEventHandler mouseDownHandler = (object msender, MouseEventArgs me) => {
    this.OnMouseDown(me);
};
foreach(Control c in this.Controls) {
    c.MouseDown += mouseDownHandler;
}

EDIT 2:

Based on the new code you added to the question you seem to have forgotten to subscribe to the events for panel2 :

this.panel2.DragDrop += new System.Windows.Forms.DragEventHandler(this.Panel2DragDrop);
this.panel2.DragEnter += new System.Windows.Forms.DragEventHandler(this.Panel2DragEnter);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM