实现无边框窗体的拖动功能。
[DllImport("user32.dll")]
public static extern bool ReleaseCapture(); [DllImport("user32.dll")]
public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam); bool _BeginMove = false;//初始化鼠标位置
int _CurrentXPosition;
int _CurrentYPosition; private void frmMain_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
_BeginMove = true;
_CurrentXPosition = Control.MousePosition.X;//鼠标的x坐标为当前窗体左上角x坐标
_CurrentYPosition = Control.MousePosition.Y;//鼠标的y坐标为当前窗体左上角y坐标
}
} private void frmMain_MouseMove(object sender, MouseEventArgs e)
{
if (_BeginMove)
{
this.Left = Control.MousePosition.X - _CurrentXPosition;//根据鼠标x坐标确定窗体的左边坐标x
this.Top = Control.MousePosition.Y - _CurrentYPosition;//根据鼠标的y坐标窗体的顶部,即Y坐标
_CurrentXPosition = Control.MousePosition.X;
_CurrentYPosition = Control.MousePosition.Y;
}
} private void frmMain_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
_CurrentXPosition = 0; //设置初始状态
_CurrentYPosition = 0;
_BeginMove = false;
}
} public void InitMoveWindowEvent(Control ctrl)
{
ctrl.MouseDown = frmMain_MouseDown;
ctrl.MouseMove = frmMain_MouseMove;
ctrl.MouseUp = frmMain_MouseUp;
}
评论