Drag and Drop Example

JDYoder

Centurion
Joined
Nov 18, 2003
Messages
144
I cannot figure this one out: Can anyone create an example where you drag and drop a label onto a panel? Thanks.
 
For a card game "table top" interface that allows the user to drag and drop playing cards between hands, onto the table, etc.
 
Hmm, I really wouldn't recommend using controls for this, but...

Code:
    public partial class Form1 : Form
    {
        int _x, _y;
        bool _moving;

        public Form1()
        {
            _moving = false;

            InitializeComponent();
        }

        private void label1_MouseDown(object sender, MouseEventArgs e)
        {
            _x = e.X;
            _y = e.Y;

            _moving = true;
        }

        private void label1_MouseMove(object sender, MouseEventArgs e)
        {
            if (_moving)
            {
                label1.Left += e.X - _x;
                label1.Top += e.Y - _y;
            }
        }

        private void label1_MouseUp(object sender, MouseEventArgs e)
        {
            if (_moving)
            {
                if (Rectangle.Intersect(new Rectangle(label1.Left, label1.Top, label1.Left + label1.Width, label1.Top + label1.Height), new Rectangle(panel1.Left, panel1.Top, panel1.Left + panel1.Width, panel1.Top + panel1.Height)) != null)
                {
                    panel1.Controls.Add(label1);
                }
                _moving = false;
            }
        }
    }

Disclaimer - the above is untested. :)
 
If I'm understanding correctly, that could work for one panel, but with multiple panels (and each of those existing in their own user controls, which are nested in another user control) I assumed drag and drop is the way to go. Maybe I'm wrong and what you have can work, but I need the controls/panels to be autonomous and not have to rely on any form code, but have all the card dropping/lifting/moving encapsulated within the controls while "talking" to one another.

Does that make sense and dictate that drag and drop is more practical, or am I not understanding what you're getting at?
 
If you've got all that going on, I would have to say it would be easier to drop the controls and just do all the drawing yourself and not have to worry about all that. Drag and drop in this case doesn't sound like it would be easier. That's just my opinion though. :)
 
It doesn't look like it should be too difficult to swap that code into a subclassed control or a separate control dragging class. You could even use the same (but slightly-modified) form-level event handlers to handle multiple controls. You might want to consider a less controls-based solution, depending on how concerned you are about how polished the final result will be.

As far as the more specific logic (controls "talking" to one another), thats more of a game logic issue than a UI issue.
 
Back
Top