Daniel Abou Chleih
Daniel Abou Chleih

Reputation: 2469

Drag/Drop Form via control and MouseEventArgs

I am currently using the code mentioned to move my form when clicking and moving the mouse on a specific control(in this case toolStrip).

private void toolStrip1_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left) //Wenn die linke Maustaste gedrückt wurde,
            FormMouseDownLocation = e.Location; //wird die Position der Maus gespeichert
    }

    private void toolStrip1_MouseMove(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left) //Wird die Linke taste gedrückt und bewegt,
        {
            this.Left += e.X - FormMouseDownLocation.X; //so verschiebt sich das Fenster bei jeder Bewegung um die Positionänderung der Maus (hier die X Pos)

            this.Top += e.Y - FormMouseDownLocation.Y; //so verschiebt sich das Fenster bei jeder Bewegung um die Positionänderung der Maus (hier die Y Pos)
        }
    }

Now I have a problem. The cursor is moving faster than the form, so often the cursor leaves the toolStrip and the form stops moving. This only happens, when I use this code combined with a control other than the mainform.

Is there any solution to this behaviour or maybe a better way to change the position of a form when clicking on another control?

Thanks in advance

Additional info: I am using winforms, FormBorderStyle: None

Upvotes: 1

Views: 867

Answers (2)

Hans Passant
Hans Passant

Reputation: 941465

This is a common problem, you have to capture the mouse to ensure you are still getting MouseMove events when the cursor moves outside of the toolstrip window. An issue with any window but more likely with a toolstrip because they tend to be slender. Fix:

private void toolStrip1_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left) {
        FormMouseDownLocation = e.Location;
        toolStrip1.Capture = true;
    }
}

private void toolStrip1_MouseUp(object sender, MouseEventArgs e)
{
    toolStrip1.Capture = false;
}

Please do pick better variable names. "FormMouseDownLocation" is extraordinarily inaccurate, the location is completely unrelated to the form.

Upvotes: 3

roybalderama
roybalderama

Reputation: 1640

You can refer to this. You can use a panel or even any object that you can use as header for example. Please check on the link. Not the part where they use WndProc

Upvotes: 0

Related Questions