winform窗体的样式很单一,不够漂亮,往往我们需要对窗体进行重写,但是我们又要保留在重写前窗体本身带的功能,例如拖动窗体的头进行移动之类的。
一下方式可以实现该方法:
[DllImport("user32")] public static extern int ReleaseCapture(); [DllImport("user32")] public static extern int SendMessage(IntPtr hwnd, int msg, int wp, int lp); /// <summary> /// 是否允许移动 /// </summary> bool IsMove = false; /// <summary> /// 判断鼠标是否在可移动范围内按下 /// </summary> private void Form_MouseDown(object sender, MouseEventArgs e) { if (e.Button == System.Windows.Forms.MouseButtons.Left) { Rectangle rect = new Rectangle(1, 1, this.Width - 70, labMin.Height); //允许拖动的矩形范围 this.IsMove = rect.Contains(new Point(e.X, e.Y)); //鼠标按下的点是否在允许拖动范围内 } } /// <summary> /// 鼠标弹起时取消移动 /// </summary> private void Form_MouseUp(object sender, MouseEventArgs e) { this.IsMove = false; } /// <summary> /// 移动窗体 /// </summary> private void Form_MouseMove(object sender, MouseEventArgs e) { if (this.IsMove && e.Button == System.Windows.Forms.MouseButtons.Left && this.WindowState != FormWindowState.Maximized) { ReleaseCapture(); SendMessage(Handle, 274, 61440 + 9, 0); return; } }