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)
{
//做一些需要的事情
}