Distinguishing between Click and DoubleClick events in C#

被刻印的时光 ゝ 提交于 2021-02-08 03:38:26

问题


I currently have a NotifyIcon as part of a Windows Form application. I would like to have the form show/hide on a double click of the icon and show a balloon tip when single clicked. I have the two functionalities working separately, but I can't find a way to have the app distinguish between a single click and double click. Right now, it treats a double click as two clicks.

Is there a way to block the single click event if there is a second click detected?


回答1:


There are 2 different kinds of events.

Click/DoubleClick

MouseClick / MouseDoubleClick

The first 2 only pass in EventArgs whereas the second pass in a MouseEventArgs which will likely allow you additional information to determine whether or not the event is a double click.

so you could do something like;

obj.MouseClick+= MouseClick;
obj.MouseDoubleClick += MouseClick;
// some stuff

private void MouseClick(object sender, MouseEventArgs e)
{
    if(e.Clicks == 2) { // handle double click }
}



回答2:


Unfortunately the suggested handling of MouseClick event doesn't work for NotifyIcon class - in my tests e.MouseClicks is always 0, which also can be seen from the reference source.

The relatively simple way I see is to delay the processing of the Click event by using a form level flag, async handler and Task.Delay :

bool clicked;

private async void OnNotifyIconClick(object sender, EventArgs e)
{
    if (clicked) return;
    clicked = true;
    await Task.Delay(SystemInformation.DoubleClickTime);
    if (!clicked) return;
    clicked = false;
    // Process Click...
}

private void OnNotifyIconDoubleClick(object sender, EventArgs e)
{
    clicked = false;
    // Process Double Click...
}

The only drawback is that in my environment the processing of the Click is delayed by half second (DoubleClickTime is 500 ms).



来源:https://stackoverflow.com/questions/44184040/distinguishing-between-click-and-doubleclick-events-in-c-sharp

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