C#实现无标题窗体拖动方法封装提取及应用
方法封装提取代码如下:
using System; using System.Collections.Generic; using System.Text; //Point using System.Drawing; //DllImport using System.Runtime.InteropServices; //MouseEventArgs using System.Windows.Forms; namespace FinancialManage.com.smile { public class SmilePublicLibrary { #region 鼠标拖动控件或窗体,实现窗体的移动 bool beginMove = false;//初始化 Point winFormCPoint = new Point(0, 0); //导入DLL [DllImport("user32.dll")] public static extern bool GetCursorPos(out Point pt); public void FMouseDown(MouseEventArgs e) { if (e.Button == MouseButtons.Left) { beginMove = true; GetCursorPos(out winFormCPoint); //winFormCPoint.X = MousePosition.X;//鼠标的x坐标为当前窗体左上角x坐标 //winFormCPoint.Y = MousePosition.Y;//鼠标的y坐标为当前窗体左上角y坐标 } } public void FMouseMove(Control control) { if (beginMove) { Point p = new Point(0,0); GetCursorPos(out p); control.Left += p.X - winFormCPoint.X;//根据鼠标x坐标确定窗体的左边坐标x control.Top += p.Y - winFormCPoint.Y;//根据鼠标的y坐标窗体的顶部,即Y坐标 winFormCPoint.X = p.X; winFormCPoint.Y = p.Y; } } public void FMouseUp(MouseEventArgs e) { if (e.Button == MouseButtons.Left) { winFormCPoint.X = 0; //设置初始状态 winFormCPoint.Y = 0; beginMove = false; } } #endregion } }
方法应用:
SmilePublicLibrary SPL = new SmilePublicLibrary(); #region 实现窗体的移动 bool beginMove = false;//初始化 Point winFormCPoint = new Point(0, 0); //拖动窗体部分 private void Login_MouseDown(object sender, MouseEventArgs e) { SPL.FMouseDown(e); } private void Login_MouseMove(object sender, MouseEventArgs e) { SPL.FMouseMove(this); } private void Login_MouseUp(object sender, MouseEventArgs e) { SPL.FMouseUp(e); } //拖动图片部分 private void pictureBox1_MouseDown(object sender, MouseEventArgs e) { SPL.FMouseDown(e); } private void pictureBox1_MouseMove(object sender, MouseEventArgs e) { SPL.FMouseMove(this); } private void pictureBox1_MouseUp(object sender, MouseEventArgs e) { SPL.FMouseUp(e); } #endregion