How to handle WinForms control click event when it

2019-05-26 05:56发布

问题:

I need to differentiate between a single click and a double click but I need to do this during the click event. I need this because if there's a single click I want to call Function A and if there's a double click I want to call Function B. But Function A must be called only in case of a single click.

How may I achieve this using standard Winforms in C# (or VB)?

回答1:

click and double click can be handled seperately

click -> http://msdn.microsoft.com/en-US/library/system.windows.forms.control.click(v=vs.80).aspx

double click -> http://msdn.microsoft.com/en-US/library/system.windows.forms.button.doubleclick(v=vs.80).aspx



回答2:

You will need to use a timer wait "some amount of time" after the click event to determine if the click was a single click. You can use the SystemInformation.DoubleClickTime property to determine the maximum interval between clicks that the system will consider sequential clicks a double click. You would probably want to add a little padding to this.

In your click handler, increment a click counter and start the timer. In the double click handler, set a flag to denote a double click occurred. In the timer handler, check to see if the double click event was raised. If not, it was a single click.

Something like this:

private bool _doubleClicked = false;
private Timer _clickTrackingTimer = 
    new Timer(SystemInformation.DoubleClickTimer + 100);


private void ClickHandler(object sender, EventArgs e)
{
    _clickTrackingTimer.Start();
}

private void DoubleClickHandler(object sender, EventArgs e)
{
    _doubleClicked = true;
}

private void TimerTickHandler(object sender, EventArgs e)
{
    _clickTrackingTimer.Stop();

    if (!_doubleClicked)
    {
        // single click!
    }

    _doubleClicked = false;
}


回答3:

Another options is to create a custom control which derives from Button, and then call the SetStyles() method, which is a protected method) in the constructor and set the ControlStyles flag

class DoubleClickButton : Button
{
    public DoubleClickButton() : base()
    {

       SetStyle(ControlStyles.StandardDoubleClick, true);
    }
}