bool IsLeftPressd = false;
int MouseLeft, MouseRight, oldX, oldY;//辨别保存鼠标当前点击地x,y坐标,和当前窗体地x,y
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
IsLeftPressd = true;//当鼠标左键按下设置为真,松开为假
oldX =this.Location .X ;//这些都是保存当前窗体位置地X
oldY = this.Location.Y;//这些都是保存当前窗体位置地X
MouseLeft = MousePosition.X;//这些都是保存当前鼠标位置地X
MouseRight = MousePosition .Y ;//这些都是保存当前鼠标位置地Y
}
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
IsLeftPressd = false;//松开鼠标后设置为假
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
if (IsLeftPressd)//判别能否按下啦鼠标左键,且没有松开
{
this.Location = new Point(oldX + MousePosition.X - MouseLeft, oldY + MousePosition.Y - MouseRight);//将以前地窗体X,Y辨别加上鼠标地偏移量!
}
}
本文介绍了一个使用C#实现鼠标拖动窗体的基本示例。通过监听鼠标按下、移动及释放事件,实现了窗体随鼠标拖动而移动的功能。代码详细展示了如何捕捉鼠标动作并据此更新窗体的位置。

被折叠的 条评论
为什么被折叠?



