FormBordStyle属性设为None
方法1
窗体里面加个Label控件作为“标题栏”
绑定Label的MouseMove和MouseDown事件
代码如下:
private int mouseX;
private int mouseY;
private void label1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
mouseX = e.X;
mouseY = e.Y;
}
}
private void label1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
this.Location = new Point(this.Location.X + (e.X - mouseX), this.Location.Y + (e.Y - mouseY));
}
}
实现效果:鼠标左键按住Label拖动即可实现窗体拖动
方法2
直接绑定窗体的MouseDown事件
代码如下:
[DllImport("user32.dll")]
public static extern bool ReleaseCapture();
[DllImport("user32.dll")]
public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
public const int WM_SYSCOMMAND = 0x0112;
public const int SC_MOVE = 0xF010;
public const int HTCAPTION = 0x0002;
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
//拖动窗体
ReleaseCapture();
SendMessage(this.Handle, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0);
}
参考:原文地址
实现效果:鼠标左键按住窗体任意位置拖动即可实现窗体拖动
方法2有大佬能解释下原理吗?在线求助