PaulD1983
PaulD1983

Reputation: 53

C# Visual Studio Windows Forms Move Object With Mouse Click

My forms consists of 4 labels that i would like to be click and dropped at a location. I need to be able to set the movObj as a type e.g. Label1 = movOject. Im asking this question to write each label name to the movObj. I know i can just put this whole code in each label click event but i like my code to be as short as possible. Ill handle the drop event once i figured this out so this question is not about that. Just setting movObj to the label clicked. Then it can moved to its possition. Help appreciated.

private Point firstPoint = new Point();
    public void INIT()
    {
        movObj.MouseDown += (ss, ee) =>
        {
            if (ee.Button == System.Windows.Forms.MouseButtons.Left) { firstPoint = Control.MousePosition; }
        };

        movObj.MouseMove += (ss, ee) =>
        {
            if (ee.Button == System.Windows.Forms.MouseButtons.Left)
            {
                //creates temp point
                Point temp = Control.MousePosition;
                Point res = new Point(firstPoint.X - temp.X, firstPoint.Y - temp.Y);

                //apply value to object
                movObj.Location = new Point(movObj.Location.X - res.X, movObj.Location.Y - res.Y);

                //updates first point
                firstPoint = temp;
            }
        };
    }

enter image description here

Upvotes: 0

Views: 1180

Answers (1)

Racil Hilan
Racil Hilan

Reputation: 25341

The signature of the events is something like:

event(object sender, EventArgs e)

In your code, ss is the sender and ee is the e.

It seems you know how to use EventArgs because you're using ee in your code. Now, the sender is the object that caused the event. In your case it is the label that was clicked. You can simply cast it from object to Label like this:

Label myLabel = (Label)sender;

and then you can get its text using myLabel.Text.

Upvotes: 1

Related Questions