MonthCalendar(日历控件)扩展DoubleClick事件
转自海道的博客
C#初学并不是很难,学过C,学过JAVA就能很容易入门,但仅仅是入门而已!真正的较量是在开发过程中碰到的一些实际的问题,昨天在开发一个和日历控件(MonthCalendar)有关联的项目,本想使用DoubleClick事件使得控件关闭然后传值,就这么简单!可是发现微软既然没有提供MonthCalendar中DoubleClick事件,原因不知为何,但问题必须解决,没办法,只能亲手扩展了!
下面就与大家一起分享解决方法!其中参考国外网的一些代码!
首先需要新建一个自定义控件继承MonthCalendar
其中重写几个重要的方法如OnMouseDown和OnDoubleClick方法即可
代码区域
public partial class Cldar : MonthCalendar
{
private Point m_LastClickPosition;
private long m_LastClickTime;
private Boolean m_LastClickRaisedDoubleClick;
public Cldar()
{
InitializeComponent();
}
protected override void OnPaint(PaintEventArgs pe)
{
// TODO: Add custom paint code here
// Calling the base class OnPaint
base.OnPaint(pe);
}
/** <summary>
/// ModeChanged Event.
/// </summary>
[Browsable(true)]
[Category("Basic_Event"), Description("觸發MonthCalendar雙擊時的事件.")]
public event EventHandler DoubleClick;
protected override void OnDoubleClick(EventArgs e)
{
DoubleClick(this, e);
base.OnDoubleClick(e);
}
bool IsInDoubleClickArea(Point Point1, Point Point2)
{
return Math.Abs(Point1.X - Point2.X) <= SystemInformation.DoubleClickSize.Width &&
Math.Abs(Point1.Y - Point2.Y) <= SystemInformation.DoubleClickSize.Height;
}
protected override void OnMouseDown(MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
if (!m_LastClickRaisedDoubleClick && System.DateTime.Now.Ticks - m_LastClickTime <= SystemInformation.DoubleClickTime * 10000 && IsInDoubleClickArea(m_LastClickPosition, Cursor.Position))
{
OnDoubleClick(EventArgs.Empty);
m_LastClickRaisedDoubleClick = true;
}
else
{
m_LastClickRaisedDoubleClick = false;
}
m_LastClickPosition = Cursor.Position;
m_LastClickTime = System.DateTime.Now.Ticks;
}
base.OnMouseDown(e);
}
}