很多时候,在winform项目中,为了实现现代化的UI,我们通常会把窗体设置为无边框,然后使用Panel绘制窗体,此时则需要实现拖拽Panel即可拖拽窗体,这里记录一个我用了很久的工具类。
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Kakkk.Utils
{
public class DragControl
{
private static bool isMouseDown = false;
private static Point mouseOffset;
private static Form _form;
public DragControl() { }
/// <summary>
/// 给窗体添加拖拽事件
/// </summary>
/// <param name="control">控件对象</param>
public static void bindControl(Control control)
{
if (control == null)
{
return;
}
_form = control.FindForm();
control.MouseMove += new MouseEventHandler(control_MouseMove);
control.MouseDown += new MouseEventHandler(control_MouseDown);
control.MouseUp += new MouseEventHandler(control_MouseUp);
}
private static void control_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
Control control = sender as Control;
int offsetX = -e.X;
int offsetY = -e.Y;
if (!(control is Form))
{
offsetX = offsetX - control.Left;
offsetY = offsetY - control.Top;
}
if (_form.FormBorderStyle != FormBorderStyle.None)
{
offsetX = offsetX - SystemInformation.FrameBorderSize.Width;
offsetY = offsetY - SystemInformation.FrameBorderSize.Height - SystemInformation.CaptionHeight;
}
mouseOffset = new Point(offsetX, offsetY);
isMouseDown = true;
}
}
private static void control_MouseMove(object sender, MouseEventArgs e)
{
if (isMouseDown)
{
Point mouse = Control.MousePosition;
mouse.Offset(mouseOffset.X, mouseOffset.Y);
_form.Location = mouse;
}
}
private static void control_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
isMouseDown = false;
}
}
}
}
使用:在窗体的构造方法使用
public MainForm()
{
InitializeComponent();
DragControl.bindControl(TopPanel);
}