C# winform 拖拽效果

时间:2023-03-08 17:41:57
C# winform 拖拽效果
        //是否在拖拽
bool isDrag = false;
//鼠标相对于button控件左上角的坐标
Point contextbtnPoint = Point.Empty;
private void button1_MouseDown(object sender, MouseEventArgs e)
{
isDrag = true;
if (e.Button == MouseButtons.Left)
{
contextbtnPoint = button1.PointToClient(Control.MousePosition); //鼠标相对于button左上角的坐标
}
}
private void button1_MouseMove(object sender, MouseEventArgs e)
{
if (isDrag)
{
Point formPoint = this.PointToClient(Control.MousePosition);//鼠标相对于窗体左上角的坐标
int x = formPoint.X - contextbtnPoint.X;
int y = formPoint.Y - contextbtnPoint.Y;
button1.Location = new Point(x, y);
}
}
private void button1_MouseUp(object sender, MouseEventArgs e)
{
if (isDrag)
{
isDrag = false;
}
}