3. Detecting a Change in Monitor State
The PowerManager class supports a number of events that help your application react to specific power conditions. For example, the BatteryLifePercentChanged
event lets you monitor the battery state and close the application
before power runs out. You can also keep track of the power source
using the PowerSourceChanged event and suggest the user close
your application when the system is running on the battery, in order to
conserve battery power for more important tasks.
An extremely useful event is IsMonitorOnChanged.
If your application monitors this event, it won't try to interact with
the user when the user clearly can't see the output of your
application. Listing 2 shows how to use this event.
Example 2. Handling a monitor state change event
public frmMain() { // Perform standard initialization. InitializeComponent();
// Add an event handler for monitor state changes. PowerManager.IsMonitorOnChanged += new EventHandler(PowerManager_IsMonitorOnChanged); }
void PowerManager_IsMonitorOnChanged(object sender, EventArgs e) { // Just show the monitor state. if (PowerManager.IsMonitorOn) lstData.Items.Add("The monitor is on!"); else lstData.Items.Add("The monitor is off!"); }
|
As with all events, Visual Studio helps you create the code in the frmMain() constructor. As soon as you type +=,
the IDE displays a message that tells you to press Tab to create the
event handler code. You press Tab a second time to create the event
handler itself, PowerManager_IsMonitorOnChanged().
The example code simply outputs a message
in this case. It outputs one message when the monitor is on and another
when the monitor is off, as shown in Figure 2.
All you need do to see the results of this example is set Windows to
turn the monitor off after a minute and then wait for the monitor to
turn itself off. The code uses the PowerManager.IsMonitorOn property to determine the current monitor state.