Handling system events

This recipe covers handling the OnRestored system event.

Getting ready

The complete code for this example is available in Ch01_Example06.

How to do it...

Replace Main() with the following code:

public class AppMain
{
 static bool _done = false;
 public static void Main (string[] args){
  
  SystemEvents.OnRestored += HandleSystemEventsOnRestored;
  while(!_done)  {
   SystemEvents.CheckEvents();
   // Loop until application minimized then restored.
  }
 }

 static void HandleSystemEventsOnRestored (object sender, RestoredEventArgs e)
 {
  Console.WriteLine ("System restored, ok to shut down");
  _done = true;
 }
}

How it works...

This code starts by wiring an OnRestored event handler to global class SystemEvents. We then loop until the _done bool is set to true. Within our loop we poll SystemEvents.CheckEvents() to see if any events have occurred. If an OnRestored event occurs, our event handler will be fired.

Our event handler HandeSystemEventsOnRestored() simply writes out a message to the console, then sets the _done bool to true, causing our loop to end, and our program to exit.

Run this example, then minimize the simulator or change applications on your device. When you refocus the application, it will fire the OnRestored event, causing your program to exit.