C#拖动鼠标移动Form窗体,移动Panel面板通用类(FormDragDrop)
效果图
FormDragDrop 类
C# 全选
/// <summary>
/// 拖动鼠标移动Form窗体,移动Panel面板通用类
/// </summary>
public class FormDragDrop
{
private Point _MouseOffset;
private bool _IsMouseDown = false;
private Control _container;
private Control _handleControl;
/// <summary>
/// 主方法
/// </summary>
/// <param name="dragControl">拖动的组件(容器或窗体)</param>
/// <param name="container">容器或窗体</param>
public static void Handle(Control dragControl, Control container)
{
FormDragDrop handle = new FormDragDrop
{
_handleControl = dragControl,
_container = container
};
handle.HandleEvents();
}
/// <summary>
/// 绑定事件
/// </summary>
private void HandleEvents()
{
_handleControl.MouseDown += On_MouseDown;
_handleControl.MouseMove += On_MouseMove;
_handleControl.MouseUp += On_MouseUp;
}
/// <summary>
/// 按下鼠标
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void On_MouseDown(object sender, MouseEventArgs e)
{
int xOffset;
int yOffset;
//鼠标点击组件或窗体的坐标
if (e.Button == MouseButtons.Left)
{
if (_container is Form)
{
xOffset = -e.X;
yOffset = -e.Y;
_MouseOffset = new Point(xOffset, yOffset);
}
else
{
xOffset = e.X;
yOffset = e.Y;
_MouseOffset = new Point(xOffset, yOffset);
}
_IsMouseDown = true;
}
}
Point _CurrentTempPoint;
/// <summary>
/// 移动鼠标
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void On_MouseMove(object sender, MouseEventArgs e)
{
if (_IsMouseDown)
{
if (_container is Form)
{
_CurrentTempPoint = Control.MousePosition; //鼠标位置在屏幕的坐标
_CurrentTempPoint.Offset(_MouseOffset.X, _MouseOffset.Y);
_container.Location = _CurrentTempPoint;
}
else
{
var x = e.Location.X - _MouseOffset.X;
var y = e.Location.Y - _MouseOffset.Y;
_CurrentTempPoint = _container.Location;
_CurrentTempPoint.Offset(x, y);
_container.Location = _CurrentTempPoint;
}
}
}
/// <summary>
/// 释放鼠标
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void On_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
_IsMouseDown = false;
}
}
}
使用方法
1、拖动窗体
C# 全选
//拖拽主窗体
FormDragDrop.Handle(this.pnlTitle, this);
2、拖动Panel组件
C# 全选
//拖拽工具箱面板
FormDragDrop.Handle(pnlToolTitle, pnlTool);
版权声明:本文为开发框架文库发布内容,转载请附上原文出处连接
NewDoc C/S框架网