在表單的類中聲明兩個變數private Point mouseOffset; //記錄滑鼠指標的座標
private bool isMouseDown = false; //記錄滑鼠按鍵是否按下
建立該表單 MouseDown事件的相應處理常式,注示部分為座標的補償private void Form1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
int xOffset;
int yOffset;
if (e.Button == MouseButtons.Left)
{
xOffset = -e.X /*- SystemInformation.FrameBorderSize.Width*/;
yOffset = -e.Y /*- SystemInformation.CaptionHeight - SystemInformation.FrameBorderSize.Height*/;
mouseOffset = new Point(xOffset, yOffset);
isMouseDown = true;
}
}
建立該表單的 MouseMove事件的相應處理常式private void Form1_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (isMouseDown)
{
Point mousePos = Control.MousePosition;
mousePos.Offset(mouseOffset.X, mouseOffset.Y);
Location = mousePos;
}
}
建立該表單的MouseUp事件的相應處理常式private void Form1_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
{
// 修改滑鼠狀態isMouseDown的值
// 確保只有滑鼠左鍵按下並移動時,才移動表單
if (e.Button == MouseButtons.Left)
{
isMouseDown = false;
}
}