#region 移动无边窗体 [DllImport("user32.dll")] public static extern bool ReleaseCapture(); [DllImport("user32.dll")] public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam); public const int WM_SYSCOMMAND = 0x0112; public const int SC_MOVE = 0xF010; public const int HTCAPTION = 0x0002; #endregion #region 事件 private void FrmLogin_MouseDown(object sender, MouseEventArgs e) { ReleaseCapture(); SendMessage(this.Handle, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0); } #endregion
bool beginMove = false;//初始化 int currentXPosition; int currentYPosition; //鼠标移动事件 private void Form1_MouseMove(object sender, MouseEventArgs e) { if (beginMove) { this.Left += MousePosition.X - currentXPosition;//根据鼠标x坐标确定窗体的左边坐标x this.Top += MousePosition.Y - currentYPosition;//根据鼠标的y坐标窗体的顶部,即Y坐标 currentXPosition = MousePosition.X; currentYPosition = MousePosition.Y; } } private void Form1_MouseDown(object sender, MouseEventArgs e) { beginMove = true; currentXPosition = MousePosition.X;//鼠标的x坐标为当前窗体左上角x坐标 currentYPosition = MousePosition.Y;//鼠标的y坐标为当前窗体左上角y坐标 } private void Form1_MouseUp(object sender, MouseEventArgs e) { beginMove = false;//停止移动 } private void Form1_MouseLeave(object sender, EventArgs e) { currentXPosition = 0; //设置初始状态 currentYPosition = 0; beginMove = false; }