基本思路:定义一个组件,传需要在该控件上实现划屏的控件给该组件,该组件通过注册该控件的MouseMove和MouseUp事件,通过这两个事件来注册向上向下向左向右划的事件。
一、添加组件
1、新建组件
项目名右击->[添加]->[组件]->[名称]输入TouchController.cs。生成一个以TouchController为类名的组件。
2、添加字段
private Control _control = null;//控件
private bool _bIsMoved = false;//标识是否正在移动。目的获取{dy}次接触屏幕的坐标。
private int _nX;//{dy}次接触屏幕的坐标水平分量x
private int _nY;//{dy}次接触屏幕的坐标垂直分量y
3、添加方法
/// <summary>
/// 设置控件
/// </summary>
/// <param name="control"></param>
public void SetControl(Control control)
{
_control = control;
if (_control != null)
{
_control.MouseMove += new MouseEventHandler(Control_MouseMove);
_control.MouseUp += new MouseEventHandler(Control_MouseUp);
}
}
4、添加属性
/// <summary>
/// 获取或设置控件
/// </summary>
public Control Control
{
get
{
return _control;
}
set
{
this.SetControl(value);
}
}
5、编写划屏事件数据
/// <summary>
/// 划屏事件数据
/// </summary>
public class TouchEventArgs : EventArgs
{
private Point _pStart;
private Point _pEnd;
/// <summary>
/// 开始坐标
/// </summary>
public Point SPoint
{
get
{
return _pStart;
}
set
{
_pStart = value;
}
}
/// <summary>
/// 结束坐标
/// </summary>
public Point EPoint
{
get
{
return _pEnd;
}
set
{
_pEnd = value;
}
}
/// <summary>
/// 构造函数
/// </summary>
public TouchEventArgs()
{
_pStart = new Point(0, 0);
_pEnd = new Point(0, 0);
}
/// <summary>
/// 构造函数
/// </summary>
/// <param name="pStart"></param>
/// <param name="pEnd"></param>
public TouchEventArgs(Point pStart, Point pEnd)
{
_pStart = pStart;
_pEnd = pEnd;
}
}
5、注册划屏事件
public delegate void TouchEvent(object sender, TouchEventArgs e);//事件代理
public event TouchEvent TouchUp;//向上划的事件
public event TouchEvent TouchDown;//向下划的事件
public event TouchEvent TouchLeft;//向左划的事件
public event TouchEvent TouchRight;//向右划的事件
//获取{dy}次触屏坐标
private void Control_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left && !_bIsMoved)
{
_bIsMoved = true;
_nX = e.X;
_nY = e.Y;
}
}
//离开屏幕时,坐标和{dy}次触屏坐标的对比,注册了向上向下向左向右划的事件
private void Control_MouseUp(object sender, MouseEventArgs e)
{
int X = e.X - _nX;
int Y = e.Y - _nY;
if (Y > -X && Y > X)
{
#region ↑向上划
if (TouchUp != null)
{
TouchUp(sender, new TouchEventArgs(new Point(_nX, _nY), new Point(e.X, e.Y)));
}
#endregion
}
else if (Y < -X && Y < X)
{
#region ↓向下划
if (TouchDown != null)
{
TouchDown(sender, new TouchEventArgs(new Point(_nX, _nY), new Point(e.X, e.Y)));
}
#endregion
}
else if (Y < -X && Y > X)
{
#region ←向左划
if (TouchLeft != null)
{
TouchLeft(sender, new TouchEventArgs(new Point(_nX, _nY), new Point(e.X, e.Y)));
}
#endregion
}
else if (Y > -X && Y < X)
{
#region →向右划
if (TouchRight != null)
{
TouchRight(sender, new TouchEventArgs(new Point(_nX, _nY), new Point(e.X, e.Y)));
}
#endregion
}
_bIsMoved = false;
}
二、演示
在工具栏向窗口拖一个TouchController组件,属性设置Control。之前切换到事件窗口,注册需要的向上向下向左向右划的事件,然后添加你要的代码。
下载Demo请看我的资源