Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

capture doubleclick for MonthCalendar control in windows forms app

How do I capture a doubleclick event of the MonthCalendar control? I've tried using MouseDown's MouseEventArgs.Clicks property, but it is always 1, even if I doubleclick.

like image 728
Bogdan Verbenets Avatar asked Dec 14 '11 00:12

Bogdan Verbenets


2 Answers

Do note that MonthCalendar neither shows the DoubleClick nor the MouseDoubleClick event in the Property window. Sure sign of trouble, the native Windows control prevents those events from getting generated. You can synthesize your own by watching the MouseDown events and measuring the time between clicks.

Add a new class to your project and paste the code shown below. Compile. Drop the new control from the top of the toolbox. Write an event handler for the DoubleClickEx event.

using System;
using System.Windows.Forms;

class MyCalendar : MonthCalendar {
    public event EventHandler DoubleClickEx;

    public MyCalender() {
        lastClickTick = Environment.TickCount - SystemInformation.DoubleClickTime;
    }

    protected override void OnMouseDown(MouseEventArgs e) {
        int tick = Environment.TickCount;
        if (tick - lastClickTick <= SystemInformation.DoubleClickTime) {
            EventHandler handler = DoubleClickEx;
            if (handler != null) handler(this, EventArgs.Empty);
        }
        else {
            base.OnMouseDown(e);
            lastClickTick = tick;
        }
    }

    private int lastClickTick;
}
like image 161
Hans Passant Avatar answered Sep 26 '22 18:09

Hans Passant


You'll need to keep track of the click events yourself. You need to use the DateSelected event to mark when a date is clicked, and the DateChanged event to 'reset' the time span so you don't count clicking different dates as a double click.

Note: if you use a mouse down event you will get buggy behavior

The mouse down event occurs no matter what is clicked, for example clicking on the month / year etc header of the Calendar will be registered just the same as clicking a real date. Hence the use of DateSelected instead of the mouse down event.

private DateTime last_mouse_down = DateTime.Now;

private void monthCalendar_main_DateSelected(object sender, DateRangeEventArgs e)
{
    if ((DateTime.Now - last_mouse_down).TotalMilliseconds <= SystemInformation.DoubleClickTime)
    {
        // respond to double click
    }
    last_mouse_down = DateTime.Now;
}

private void monthCalendar_main_DateChanged(object sender, DateRangeEventArgs e)
{
    last_mouse_down = DateTime.Now.Subtract(new TimeSpan(1, 0, 0));
}
like image 35
DAG Avatar answered Sep 24 '22 18:09

DAG