Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 918
Sabin Darkstone Avatar asked Sep 02 '25 02:09

Sabin Darkstone


2 Answers

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

like image 183
Ivan Stoev Avatar answered Sep 04 '25 16:09

Ivan Stoev


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 }
}
like image 34
Andrew Goacher Avatar answered Sep 04 '25 16:09

Andrew Goacher