#region 设置鼠标拖动控件
bool isFlag = false;//是否在拖动窗体
int enterX, enterY;
/// <summary>
/// 在指定的控件上托动窗体
/// </summary>
/// <param name="c">指定控件</param>
void ControlMouseMove(Control c)
{
c.MouseUp += C_MouseUp;
c.MouseMove += C_MouseMove;
c.MouseDown += C_MouseDown;
}
private void C_MouseDown(object sender, MouseEventArgs e)
{
isFlag = true;
enterX = e.Location.X;
enterY = e.Location.Y;
}
private void C_MouseMove(object sender, MouseEventArgs e)
{
if (isFlag)
{
Left += e.Location.X - enterX;
Top += e.Location.Y - enterY;
}
}
private void C_MouseUp(object sender, MouseEventArgs e)
{
isFlag = false;
enterX = 0;
enterY = 0;
}
#endregion
在窗体的构造函数中调用
ControlMouseMove(“这里是指定的控件”);
更新第二版写在一个方法里
/// <summary>
/// 在指定的窗体上拖动控件上移动动窗体
/// </summary>
/// <param name="frm">指定的窗体</param>
/// <param name="ctr">指定控件</param>
public static void SetDragFormByControl(Form frm,Control ctr)
{
bool isFlag = false;//是否在拖动窗体
int enterX = 0;
int enterY = 0;
ctr.MouseDown += (sender, e) =>
{
isFlag = true;
enterX = e.Location.X;
enterY = e.Location.Y;
};
ctr.MouseMove += (sender, e) =>
{
if (isFlag)
{
frm.Left += e.Location.X - enterX;
frm.Top += e.Location.Y - enterY;
}
};
ctr.MouseUp += (sender, e) =>
{
isFlag = false;
enterX = 0;
enterY = 0;
};
}