简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM