简体   繁体   中英

Distinguishing between Click and DoubleClick events in C#

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?

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

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM