-2

Whenever I move a Windows Form by some component (i.e. a Label) in the client area, I end up with a strange mouse offset in which the form does not stay visually underneath the cursor. It will still move according to my mouse location on the screen, but it dramatically shifts southeast of the cursor's position.

I've had to specify a negative offset of my own to counteract this offset; my code is as follows:

private void component_MouseDown(object sender, MouseEventArgs e)
{
    if (sender is Label)
    {
        if (e.Button == MouseButtons.Left)
        {
             mouseLoc = new Point(-(e.X + OFFSET_X), -(e.Y + OFFSET_Y));
             isMouseDown = true;
        }
    }
}

private void component_MouseMove(object sender, MouseEventArgs e)
{
    if (isTitleLabelMouseDown)
    {
        Point p = Control.MousePosition;
        p.Offset(mouseLoc);
        Location = p;
    }
}

private void component_MouseUp(object sender, MouseEventArgs e)
{
    isMouseDown = false;
}

This offset does fix the problem, but what throws me for a loop is why the form's location offsets when I move it by its client area in the first place?

Thanks!

Jeff
  • 227
  • 1
  • 4
  • 16

1 Answers1

0

You seem to be translating client coordinates to screen coordinates. There is a better way...

https://msdn.microsoft.com/en-us/library/system.windows.forms.control.pointtoscreen%28v=vs.110%29.aspx

Edit: And of course there's a better way to do this whole thing. Basically, you want to intercept the click higher up the chain and tell Windows that the click is actually in the window title, which will cause Windows to do the dragging for you...

Winforms - WM_NCHITEST message for click on control

Community
  • 1
  • 1
glenebob
  • 1,943
  • 11
  • 11