Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One function for two events

Tags:

c#

I have this code that I attach to the DoubleClick event on the Tray Icon for my app:

ni.DoubleClick +=
  delegate(object sender, EventArgs args)
        {
            this.MainWindow.Show();
        };

But, is it possible to use this code for two events (DoubleClick and Click), like so:

ni.DoubleClick, ni.Click +=
  delegate(object sender, EventArgs args)
        {
            this.MainWindow.Show();
        };

Just for minimalize a code size and readability. Thanks

like image 893
Roman Nazarkin Avatar asked Nov 28 '22 02:11

Roman Nazarkin


2 Answers

Put the handler in its own function:

private void ClickHandler(object sender, EventArgs args)
{
    this.MainWindow.Show();
}

Then wire it up to both events:

ni.DoubleClick += ClickHandler;
ni.Click += ClickHandler;
like image 146
PhonicUK Avatar answered Nov 29 '22 17:11

PhonicUK


Just create EventHandler using lambda expression and add it to both event.

EventHandler e = (sender, args) => this.MainWindow.Show();
ni.DoubleClick += e;
ni.Click += e;
like image 39
tia Avatar answered Nov 29 '22 17:11

tia