1

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

Daniel Abou Chleih
  • 2,440
  • 2
  • 19
  • 31

2 Answers2

3

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.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • Thanks a lot. Worked like a charm. Sorry for the var names. It was just a example, so I thought it wouldn't matter(I would never name it toolStrip1). – Daniel Abou Chleih Mar 27 '13 at 12:15
0

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

Community
  • 1
  • 1
roybalderama
  • 1,650
  • 21
  • 38