user3002135
user3002135

Reputation: 237

Exit while loop of mouseDown event

I am trying to make my Form, which has no border, moveable with holding the left mousebutton down and exit the while loop, when releasing the mousebutton. But the code I have right now doesn't exit the loop on release.

    private void Form1_MouseDown(object sender, MouseEventArgs e)
    {
        mouseDown = true;

        while (mouseDown)
        {
            mouseX = MousePosition.X;
            mouseY = MousePosition.Y - 30;
            this.SetDesktopLocation(mouseX, mouseY);

            if (e.Button != MouseButtons.Left)
                mouseDown = false;
        }

I also tried to add a mouseUp event but it cant happen as long as mouseDown is active.

    private void Form1_MouseUp(object sender, MouseEventArgs e)
    {
        mouseDown = true;
    }

Upvotes: 0

Views: 871

Answers (2)

user3002135
user3002135

Reputation: 237

OK, I fixed it for myself.

I just did this:

private void Form1_MouseDown(object sender, MouseEventArgs e)
{
    mouseDown = true;
}

private void Form1_MouseUp(object sender, MouseEventArgs e)
{
    mouseDown = false;
}

private void Form1_MouseMove(object sender, MouseEventArgs e)
{
    if (mouseDown)
    {
        mouseX = MousePosition.X - 20;
        mouseY = MousePosition.Y - 40;
        this.SetDesktopLocation(mouseX, mouseY);
    }
}

Upvotes: 4

Valderann
Valderann

Reputation: 835

By using a loop in the on mouse up event you are locking the thread. You could use the MouseMove event with a public variable to check if the mouse is down.

Upvotes: 1

Related Questions