“Is there any way to schedule a task based on a system event?”

… such as an event written to the System Log, or a laptop losing mains power?

Windows Vista, or later?
Yes, indeedy.  Task Scheduler has this functionally built right in.

Windows 2000/XP?
But you could write a program to do that.

Something like this little Visual Basic 2005 program, for the “laptop losing mains power” example:

“Power Status” demonstrates two techniques:

  1. How to get the state of the installed battery, without resorting to calling an API such as GetSystemPowerStatus.
    We do this by using the PowerStatus class which first appeared in .Net v2.0
  2. How to detect a change from Battery power to Mains power, by capturing the PBT_APMPOWERSTATUSCHANGE event.
    By overriding the default WindowProc function, so we can check the Windows Events being sent to us by the operating system.
    When we see the PBT_APMPOWERSTATUSCHANGE event, we update the PowerStatus values and then refresh the screen.

Overriding the default WindowsProc seems very difficult to do, though it’s not.  But it only took 10 minutes of coding.  And it worked first time.

Finding the PowerStatus class, and processing the values, wasted about four hours of code experimentation.
And it still needs work.

Particularly BatteryChargeStatus.

BatteryChargeStatus is returning “undocumented” values in the 9 –> 127 range.
What I suspect is that the battery charger has two modes, Fast charge and Trickle charge.  Which is being reported.  As it’s not documented by Microsoft, I’m not sure.

The sample program is here.
The source code is here.

Comments are closed.