My first post, apologies if this has been answered already - I have searched and searched but have not found any specifics on using Custom EventArgs with existing SystemEvents.
I am trying to take advantage of the SystemEvents.PowerModeChanged type events but would like to use my own Custom EventArgs instead of the standard PowerModeChangedEventArgs. My approach was to create a class called CustomPowerModeChangedEventArgs which inherits from PowerModeChangedEventArgs and use these instead but I don't know how to tell the PowerModeChangedEventHandler to use these new CustomEvent args. My code is as follows:
//Define the custom args which inherit from the PowerModeChangedEventArgs
public class CustomPowerModeChangedEventArgs : PowerModeChangedEventArgs
{
public string batterylevel { get; set; }
}
//event raising method with CustomArgs instead of the PowerModeChangedEventArgs
protected virtual void PowerModeChanged(object source, CustomPowerModeChangedEventArgs e)
{
}
SystemEvents.PowerModeChanged += new PowerModeChangedEventHandler(PowerModeChanged);
The problem is with the PowerModeEventChangedHandler not accepting the method PowerModeChanged with the CustomArgs. Had it been a generic eventhandler I could define the args like...
public event EventHandler<CustomPowerModeChangedEventArgs> PowerModeCHanged;
...but I can't fathom how to achieve similar with a non generic event handler. I have a suspicion that it might be possible to send the new custom args to the handler using lambda expressions but I'm really not sure about this - maybe I need to define a whole new EventChangedHandler? Any advice would be greatly appreciated.
No, you don't get to decide what parameters the event handler has. Bear in mind that there's already code in the system which is going to call your event handler... how would you expect it to construct an instance of your CustomPowerModeChangedEventArgs
?
If the event had been declared using EventHandler<T>
, that still wouldn't have helped you - the code calling the event handler has already been written, and it's going to pass in a PowerModeChangedEventArgs
that it constructs, not an instance of your type.
Now you could declare your own event using your custom event-args, and then hook into the SystemEvents
so that you raise your own event (with an instance of your own event-args, however you decide to construct that) when the system event is raised... but you shouldn't expect to be able to add an event handler which requires information the event raiser (in this case the system) isn't aware of.
See more on this question at Stackoverflow