Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I move windows when Mouse Down

Tags:

c#

winforms

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

like image 689
pedram Avatar asked Dec 03 '22 04:12

pedram


2 Answers

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);
    }
}
like image 115
djdd87 Avatar answered Dec 20 '22 14:12

djdd87


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.

like image 21
Thomas Levesque Avatar answered Dec 20 '22 13:12

Thomas Levesque