现在的位置: 首页 > 综合 > 正文

(改进)UserControl的单击事件对鼠标左右键都有效,怎样使之像按钮控件那样只对鼠标左键敏感?

2013年07月25日 ⁄ 综合 ⁄ 共 1185字 ⁄ 字号 评论关闭

UserControl的单击事件对鼠标左右键都有效,怎样使之像按钮控件那样只对鼠标左键敏感?(改进)

在类的外面声明这个委托:

public delegate void MouseClickEvent(object sender, MouseEventArgs e);

在类里面重写一些方法:

/ // <summary>

/// 标记鼠标是否经历了按下移动抬起的过程。

/// </summary>

private bool _isMouseLeftButtonDownMoveUp = false;

protected override void OnMouseDown(MouseEventArgs e)

{

this._isMouseLeftButtonDownMoveUp = false;

base.OnMouseDown (e);

}

protected override void OnMouseMove(MouseEventArgs e)

{

if(e.Button == MouseButtons.Left)

{

this._isMouseLeftButtonDownMoveUp = true;

}

base.OnMouseMove (e);

}

protected override void OnMouseUp(MouseEventArgs e)

{

base.OnMouseUp (e);

if(!(this.AllowDragMove & this._isMouseLeftButtonDownMoveUp))

{

//如果被单击,而且位置还在控件范围之内,而且单击的是左键

if(e.Clicks == 1 & this.InShell(e.X, e.Y) & e.Button == MouseButtons.Left)

{

//触发MouseClick事件

this.MouseClick(this, e);

}

}

this._isMouseLeftButtonDownMoveUp = false;

}

private bool InBounds(int x, int y)

{

Point p = this.PointToScreen(new Point(x, y));

Point p1 = this.PointToScreen(new Point(0, 0));

Point p2 = this.PointToScreen(new Point(this.Width, this.Height));

if(p.X < p1.X)

{

return false;

}

if(p.X > p2.X)

{

return false;

}

if(p.Y < p1.Y)

{

return false;

}

if(p.Y > p2.Y)

{

return false;

}

return true;

}

public event MouseClickEvent MouseClick;

private void Shell_MouseClick(object sender, MouseEventArgs e)

{

//做一些需要的事情

}

抱歉!评论已关闭.