C#WinForm无边框窗体移动方法、模仿鼠标单击标题栏移动窗体位置
这里介绍俩种办法
方法一:直接通过修改窗体位置从而达到移动窗体的效果
方法二:直接伪装发送单击任务栏消息,让应用程序误以为单击任务栏从而移动窗体
新建窗体用于测试
方法一
1.定义一个位置信息Point用于存储鼠标位置
1 private Point mPoint;
2.给窗体等控件增加MouseDown和MouseMove事件
1 /// <summary> 2 /// 鼠标按下 3 /// </summary> 4 /// <param name="sender"></param> 5 /// <param name="e"></param> 6 private void panel1_MouseDown(object sender, MouseEventArgs e) 7 { 8 mPoint = new Point(e.X, e.Y); 9 } 10 11 /// <summary> 12 /// 鼠标移动 13 /// </summary> 14 /// <param name="sender"></param> 15 /// <param name="e"></param> 16 private void panel1_MouseMove(object sender, MouseEventArgs e) 17 { 18 if (e.Button == MouseButtons.Left) 19 { 20 this.Location = new Point(this.Location.X + e.X - mPoint.X, this.Location.Y + e.Y - mPoint.Y); 21 } 22 }
方法二:
1.引入下面代码 前提需要引入命名空间using System.Runtime.InteropServices
1 [DllImport("user32.dll")] 2 public static extern bool ReleaseCapture(); 3 4 [DllImport("user32.dll")] 5 public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam); 6 7 private const int VM_NCLBUTTONDOWN = 0XA1;//定义鼠标左键按下 8 private const int HTCAPTION = 2;
2.增加鼠标按下事件发送消息,让系统误以为按下是标题栏
1 /// <summary> 2 /// 鼠标按下 3 /// </summary> 4 /// <param name="sender"></param> 5 /// <param name="e"></param> 6 private void panel1_MouseDown(object sender, MouseEventArgs e) 7 { 8 //为当前应用程序释放鼠标捕获 9 ReleaseCapture(); 10 //发送消息 让系统误以为在标题栏上按下鼠标 11 SendMessage((IntPtr)this.Handle, VM_NCLBUTTONDOWN, HTCAPTION, 0); 12 }
测试效果
源代码工程文件下载
原文地址:https://www.cnblogs.com/JiYF/p/9053596.html
时间: 2024-10-06 12:00:15