private Point mouseOffset; //记录鼠标指针的坐标
private bool isMouseDown = false; //记录鼠标按键是否按下
/// <summary>
/// 递归得到指定控件偏移量X值
/// </summary>
/// <param name="sender">指定的控件</param>
/// <returns></returns>
private int GetOffsetX(Control sender)
{
if (sender == this)
{
return 0;
}
if (sender.Parent != this)
{
return sender.Left + GetOffsetX(sender.Parent);
}
else
{
return 0;
}
}
/// <summary>
/// 递归得到指定控件偏移量Y值
/// </summary>
/// <param name="sender">指定的控件</param>
/// <returns></returns>
private int GetOffsetY(Control sender)
{
if (sender == this)
{
return 0;
}
if (sender.Parent != this)
{
return sender.Top + GetOffsetY(sender.Parent);
}
else
{
return 0;
}
}
/// <summary>
/// MouseDown
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void FormTitle_MouseDown(object sender, MouseEventArgs e)
{
int xOffset;
int yOffset;
if (e.Button == MouseButtons.Left)
{
xOffset = -(e.X + GetOffsetX((Control)sender));
yOffset = -(e.Y + GetOffsetY((Control)sender));
mouseOffset = new Point(xOffset, yOffset);
isMouseDown = true;
}
}
/// <summary>
/// MouseMove
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void FormTitle_MouseMove(object sender, MouseEventArgs e)
{
if (isMouseDown)
{
Point mousePos = Control.MousePosition;
mousePos.Offset(mouseOffset.X, mouseOffset.Y);
Location = mousePos;
}
}
/// <summary>
/// MouseUp
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void FormTitle_MouseUp(object sender, MouseEventArgs e)
{
// 修改鼠标状态isMouseDown的值
// 确保只有鼠标左键按下并移动时,才移动窗体
if (e.Button == MouseButtons.Left)
{
isMouseDown = false;
}
}