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