关闭

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

1498人阅读 评论(0) 收藏 举报

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)

{

//做一些需要的事情

}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:175288次
    • 积分:2797
    • 等级:
    • 排名:第12793名
    • 原创:100篇
    • 转载:3篇
    • 译文:0篇
    • 评论:23条
    最新评论