How to handle WinForms control click event when it's not a double click

孤者浪人 提交于 2019-12-10 10:39:53

问题


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);
    }
}


来源:https://stackoverflow.com/questions/10485676/how-to-handle-winforms-control-click-event-when-its-not-a-double-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!