Pass parameter for EventHandler

I have the following EventHandler to which I have added the MusicNote music parameter:

 public void PlayMusicEvent(object sender, EventArgs e,MusicNote music) { music.player.Stop(); System.Timers.Timer myTimer = (System.Timers.Timer)sender; myTimer.Stop(); } 

I need to add a handler to Timer like this:

 myTimer.Elapsed += new ElapsedEventHandler(PlayMusicEvent(this, e, musicNote)); 

but get an error:

"Expected Method Name"

EDIT: In this case, I just pass the e from the method that contains this piece of code, how can I pass the EventArgs timer?

+69
parameter-passing c # event-handling
Dec 27 '11 at 11:43
source share
2 answers

Timer.Elapsed expects a method of a specific signature (with arguments object and EventArgs ). If you want to use your PlayMusicEvent method with an additional argument evaluated during event registration , you can use the lambda expression as an adapter:

 myTimer.Elapsed += new ElapsedEventHandler((sender, e) => PlayMusicEvent(sender, e, musicNote)); 

Edit: you can also use a shorter version:

 myTimer.Elapsed += (sender, e) => PlayMusicEvent(sender, e, musicNote); 
+175
Dec 27 '11 at 11:48
source share

If I understand your problem correctly, you are calling a method instead of passing it as a parameter. Try the following:

 myTimer.Elapsed += PlayMusicEvent; 

Where

 public void PlayMusicEvent(object sender, ElapsedEventArgs e) { music.player.Stop(); System.Timers.Timer myTimer = (System.Timers.Timer)sender; myTimer.Stop(); } 

But you need to think about where to store the note.

+3
Dec 27 '11 at 11:50
source share



All Articles