//鼠标点击控件按住不放,控件跟随移动。施放则不移动
//这里的控件可以更换为其他控件。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Test
{
public partial class Form1 : Form
{
private int ax, ay; // 定义两个变量存储鼠标的横纵坐标
public Form1()
{
InitializeComponent();
}
/// <summary>
/// 鼠标首次单击控件,记录鼠标坐标
/// </summary>
/// <param ax="int">鼠标横坐标</param>
/// <param ay="int">鼠标纵坐标</param>
private void button1_MouseDown(object sender, MouseEventArgs e)
{
ax = e.X;
ay = e.Y;
}
/// <summary>
/// 鼠标移动时,控件跟随鼠标移动。利用相对坐标计算
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
button1.Left = button1.Left + (e.X - ax);
button1.Top = button1.Top + (e.Y - ay);
}
}
}
}