public partial class Form1 : Form {
//記錄窗體的X坐標
private int startX;
//記錄窗體的Y坐標
private int startY;
public Form1() {
InitializeComponent();
}
/// <summary>
/// 鼠標點擊左鍵
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_MouseDown(object sender, MouseEventArgs e) {
//判斷點擊的是不是左鍵
if(e.Button == MouseButtons.Left) {
//得到窗體的X值
startX = e.X;
//得到窗體的Y值
startY = 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) {
//重新繪制窗體X
this.Left += e.X - startX;
//重新繪制窗體Y
this.Top += e.Y - startY;
}
}
}
摘自 :幸福的豬的專欄