pedram
pedram

Reputation: 3767

How can I move windows when Mouse Down

we able to move windows forms when we mouse down on title bar . but how can I move windows when mouse down in form ?

Upvotes: 5

Views: 13575

Answers (4)

user5583316
user5583316

Reputation:

You can't use location provided in MouseUp or Down, you should use system location like this

private Point diffPoint;
bool mouseDown = false;

private void Form1_MouseDown(object sender, MouseEventArgs e)
{
  //saves position difference
  diffPoint.X = System.Windows.Forms.Cursor.Position.X - this.Left;
  diffPoint.Y = System.Windows.Forms.Cursor.Position.Y - this.Top;
  mouseDown = true;
}

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

private void Form1_MouseMove(object sender, MouseEventArgs e)
{
  if (mouseDown)
  {
    this.Left = System.Windows.Forms.Cursor.Position.X - diffPoint.X;
    this.Top = System.Windows.Forms.Cursor.Position.Y - diffPoint.Y;
  }
}

This works, tested.

Upvotes: 0

Thomas Levesque
Thomas Levesque

Reputation: 292685

You can do it manually by handling the MouseDown event, as explained in other answers. Another option is to use this small utility class I wrote some time ago. It allows you to make the window "movable" automatically, without a line of code.

Upvotes: 4

djdd87
djdd87

Reputation: 68506

You'll need to record when the mouse is down and up using the MouseDown and MouseUp events:

private bool mouseIsDown = false;
private Point firstPoint;

private void Form1_MouseDown(object sender, MouseEventArgs e)
{
    firstPoint = e.Location;
    mouseIsDown = true;
}

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

As you can see, the first point is being recorded, so you can then use the MouseMove event as follows:

private void Form1_MouseMove(object sender, MouseEventArgs e)
{
    if (mouseIsDown)
    {
        // Get the difference between the two points
        int xDiff = firstPoint.X - e.Location.X;
        int yDiff = firstPoint.Y - e.Location.Y;

        // Set the new point
        int x = this.Location.X - xDiff;
        int y = this.Location.Y - yDiff;
        this.Location = new Point(x, y);
    }
}

Upvotes: 13

Hans Olsson
Hans Olsson

Reputation: 55049

Listen for the event when the mouse button goes down in the form and then listen for mouse moves until it goes up again.

Here's a codeproject article that shows how to do this: Move window/form without Titlebar in C#

Upvotes: 3

Related Questions