Was just messing around looking at the XNA documentation for the Game class and noticed there is a Deactivated
event and an OnDeactived
virtual method one can override.
Both creating an event handler for the Deactivated
event and overriding the OnDeactived
virtual method allows the client to handle the game losing focus.
I was wondering which approach should be used generally to handle the game losing focus. Creating an event handler or overriding the virtual method? Are there any differences between each approach?
There are two obvious differences:
OnDeactivated
within a class derived from the one declaring it - mere "other" code can only use the eventOnDeactived
, it's up to you to decide whether or not to call base.OnDeactivated
- you could effectively suppress the event, or change the parameters; invoke it before or after your own code, etc.If you're already deriving from the class, either way would work - personally I'd probably use the event more often than not, unless I wanted to take any other sort of action that could only be performed by overriding. Aside from anything else, that makes the code more portable if you want to move it anywhere else. Then again, I'm generally not a fan of inheritance anyway, so I'm biased :)
The decision of whether to override the method or use the event handler often times comes down to how much control you need to have over what happens during the execution of that method. Overriding the method gives you full control of the method, whereas the event handler only runs after the method has executed.
If you need a high level of control over what happens during that method, I would advise overriding the method. If you simply need to run some code after execution of the method, I would use the event handler.
protected override void OnDeactivated(EventArgs e)
{
//run some code before execution (anything that could effect execution)
//call the base method and fire the event
base.OnDeactivated(e);
//run some code after execution
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With