c#winform实现无边框窗体拖动
有时想弄个无标题栏的窗体,发现无标题栏后鼠标无法自由拖动窗体了。怎么办呢,
我们来解决下:
举个例子,我们在窗体中加了个Panel控件,我们想通过点击Panel控件来移动窗 体,那么我们就在Panel的MouseDown事件中添加两个方法:
using System.Runtime.InteropServices;//要引用的名称空间
[DllImport("user32.DLL", EntryPoint = "ReleaseCapture")]
private extern static void ReleaseCapture();
[DllImport("user32.DLL", EntryPoint = "SendMessage")]
private extern static void SendMessage(System.IntPtr hWnd, int wMsg, int wParam, int lParam);
//Panel的鼠标按下事件
private void panel1_MouseDown(object sender, MouseEventArgs e)
{
ReleaseCapture();
SendMessage(this.Handle, 0x112, 0xf012, 0);
}
我们还可以通过获取鼠标的位置来实现
private Point mouseInitialPoint;//用来记录按下鼠标时的鼠标初始位置
//鼠标的按下事件
private void panel1_MouseDown(object sender, MouseEventArgs e)
{
mouseInitialPoint = e.Location;
}
//鼠标的移动事件
private void panel1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
//窗体位置=原始位置+变化的位置
this.Location = new Point(this.Location.X + (e.Location.X - mouseInitialPoint.X),
this.Location.Y + (e.Location.Y - mouseInitialPoint.Y));
}
}
注:
this.Location 为窗体的位置**
e.Location为移动后鼠标的位置
mouseInitialPoint 为鼠标的位置