winfrom窗体自带的边框不好看,可以将FormBorderStyle设置为None去除边框,但这样窗体无法拖动
下面记录无边框窗体拖动的几种方法[参考其他博主的]:
1.Form触发MouseDown事件时,记录鼠标坐标:
rawPoint = e.Location;
MouseMove时根据鼠标坐标的移动偏移量,设置窗体位置同步变化:
void Form1_MouseMove(object sender, MouseEventArgs e) { if (e.Button != System.Windows.Forms.MouseButtons.Left) return; int x = e.X - rawPoint.X; int y = e.Y - rawPoint.Y; this.Location = new Point(this.Location.X + x, this.Location.Y + y); }
2.Form上方放置控件(如Label)来模拟边框,通过控件的MouseDown和MouseMove事件来实现,同方法1;
3.调用win32 api,Form的MoveDown触发时,向系统发送鼠标点击窗体非客户区的消息(模拟点击窗体边框):
[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 LeftButtonDown = 0xA1; private const int HTCaption = 0x02; private void Form1_MouseDown(object sender, MouseEventArgs e) { ReleaseCapture(); SendMessage((IntPtr)this.Handle, LeftButtonDown, HTCaption, 0); }
4.重写WndProc函数,拦截鼠标左击窗体的消息,改为左击窗体的非客户区:
protected override void WndProc(ref Message m) { switch (m.Msg) { case 0x0201: { m.Msg = 0xA1; m.WParam = new IntPtr(2); m.LParam = new IntPtr(0); } break; } base.WndProc(ref m); }
以上方式均可实现窗体拖动。
标签:IntPtr,拖动,边框,int,窗体,Location,Winform From: https://www.cnblogs.com/cfsl/p/17675151.html