自由拖动的控件
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
namespace WindowsFormsApplication8
{
public class MoveButton:Button
{
bool IsMoving = false;
Point pCtrlLastCoordinate = new Point(0, 0);
Point pCursorOffset = new Point(0, 0);
Point pCursorLastCoordinate = new Point(0, 0);
public MoveButton()
{
InitializeComponent();
}
private void InitializeComponent()
{
this.SuspendLayout();
//
// MoveButton
//
this.MouseMove += new System.Windows.Forms.MouseEventHandler(this.MoveButton_MouseMove);
this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.MoveButton_MouseDown);
this.MouseUp += new System.Windows.Forms.MouseEventHandler(this.MoveButton_MouseUp);
this.ResumeLayout(false);
}
private void MoveButton_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
IsMoving = true;
pCtrlLastCoordinate.X = Left;
pCtrlLastCoordinate.Y = Top;
pCursorLastCoordinate.X = Cursor.Position.X;
pCursorLastCoordinate.Y = Cursor.Position.Y;
}
}
private void MoveButton_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
if (this.IsMoving)
{
Point pCursor = new Point(Cursor.Position.X, Cursor.Position.Y);
pCursorOffset.X = pCursor.X - pCursorLastCoordinate.X;
pCursorOffset.Y = pCursor.Y - pCursorLastCoordinate.Y;
Left = pCtrlLastCoordinate.X + pCursorOffset.X;
Top = pCtrlLastCoordinate.Y + pCursorOffset.Y;
}
}
}
private void MoveButton_MouseUp(object sender, MouseEventArgs e)
{
if (this.IsMoving)
{
if (pCursorOffset.X == 0 && pCursorOffset.Y == 0)
{
return;
}
if ((pCtrlLastCoordinate.X + pCursorOffset.X + Width) > 0)
{
Left = pCtrlLastCoordinate.X + pCursorOffset.X;
}
else
{
Left = 0;
}
if ((pCtrlLastCoordinate.Y + pCursorOffset.Y + Height) > 0)
{
Top = pCtrlLastCoordinate.Y + pCursorOffset.Y;
}
else
{
Top = 0;
}
pCursorOffset.X = 0;
pCursorOffset.Y = 0;
}
}
}
}