您的位置:首页 > 编程语言 > C#

C#鼠标拖动窗体代码

2011-04-16 09:05 288 查看
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;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: