开发者

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 fo开发者_StackOverflow社区rm ?


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);
    }
}


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.


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#


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜