网上找了半天, 实在是受不了了, 算法和代码自己摸出来了, 别问为什么, 拿走不谢
using System.Drawing; //point 要用这个
using System.Windows.Forms;
namespace Example
{
public partial class FormThreeShow : Form
{
private static bool IsDragging = false; //用于指示当前是不是在拖拽状态
private Point StartPoint = new Point(0, 0); //记录鼠标按下去的坐标, new是为了拿到空间, 两个0无所谓的
//记录动了多少距离,然后给窗体Location赋值,要设置Location,必须用一个Point结构体,不能直接给Location的X,Y赋值
private Point OffsetPoint = new Point(0, 0);
public FormThreeShow()
{
InitializeComponent();
}
private void FormThreeShow_MouseDown(object sender, MouseEventArgs e)
{
//如果按下去的按钮不是左键就return,节省运算资源
if (e.Button != MouseButtons.Left)
{
return;
}
//按下鼠标后,进入拖动状态:
IsDragging = true;
//保存刚按下时的鼠标坐标
StartPoint.X = e.X;
StartPoint.Y = e.Y;
}
private void FormThreeShow_MouseMove(object sender, MouseEventArgs e)
{
//鼠标移动时调用,检测到IsDragging为真时
if (IsDragging == true)
{
//用当前坐标减去起始坐标得到偏移量Offset
OffsetPoint.X = e.X - StartPoint.X;
OffsetPoint.Y = e.Y - StartPoint.Y;
//将Offset转化为屏幕坐标赋值给Location,设置Form在屏幕中的位置,如果不作PointToScreen转换,你自己看看效果就好
Location = PointToScreen(OffsetPoint);
}
}
private void FormThreeShow_MouseUp(object sender, MouseEventArgs e)
{
//左键抬起时,及时把拖动判定设置为false,否则,你也可以试试效果
IsDragging = false;
}
}
}