Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does MouseEventArgs not work when used in equation

Tags:

c#

winforms

Windows Forms Application:

This has been puzzling me for hours. What I am ATTEMPTING to do is when i hold down on a label, it moves the form.

    private void label1_MouseUp(object sender, MouseEventArgs e)
    {
        KeepMoving = false;
    }

    private void label1_MouseDown(object sender, MouseEventArgs e)
    {
        KeepMoving = true;
    }

    private void label1_MouseMove(object sender, MouseEventArgs e)
    {
        if (KeepMoving == true)
            this.Location = new Point(MousePosition.X - (e.X + SystemInformation.FrameBorderSize.Width + label1.Left), MousePosition.Y - (e.Y + SystemInformation.CaptionHeight + label1.Top));

    }

is what i'm using (with a public bool KeepMoving of course.)

All works fine if I remove the e.X and e.Y, but then it is relative to the position of the top left of the label, however I want the location on the label itself.

When I use a messagebox to show me coordinates of e.X and e.Y on label, the numbers are correct showing me where on the label i clicked. When I use the point in the code above, no matter where on the label i click, the number doesn't change, and when i attempt to move it it shoots up into the 30k+ range.

Why doesn't the MouseEventArgs work in my equation? Sorry if i described poorly i tried the best i could.


1 Answers

Keep track of the intiial offset from the top-left corner of the Label and adjust the Form's location accordingly.

    public bool KeepMoving = false;
    private Point offset;

    private void label1_MouseDown(object sender, MouseEventArgs e)
    {
        KeepMoving = true;
        offset = new Point(e.X, e.Y);
    }

    private void label1_MouseUp(object sender, MouseEventArgs e)
    {
        KeepMoving = false;
    }

    private void label1_MouseMove(object sender, MouseEventArgs e)
    {
        if (KeepMoving)
        {
            Left += e.X - offset.X;
            Top += e.Y - offset.Y;
        }
    }
like image 52
JosephHirn Avatar answered Nov 27 '25 20:11

JosephHirn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!