Here I will post problems I and my colleagues met and solutions we found.

Wednesday, August 20, 2008

SystemEvents.PowerModeChanged Event and services

As I posted before I wrote small application to know how much time my daughter logged on computer. To do this I used SENS events. And then I noticed that numbers are to big. And the problem was that these events did not trigger when computer went to sleep or hibernate modes. And service did not stop either. .NET has SystemEvents.PowerModeChanged event that I decided to use. Surprise, it doesn't work from service. The solution was found in System.Management name space and ManagementEventWatcher class.

Here is the fragment of the code I used:



WqlEventQuery query = new WqlEventQuery("Win32_PowerManagementEvent");
_watcher = new ManagementEventWatcher(query);
_watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);
_watcher.Start();


when my service started.

_watcher.Stop();

when it stopped.



void watcher_EventArrived(object sender, EventArrivedEventArgs e)
{
try
{
int eventType = Convert.ToInt32(e.NewEvent.Properties["EventType"].Value);
switch (eventType)
{
case 4:
Sleep();
break;
case 7:
Resume();
break;
}
}
catch (Exception ex)
{
Log(ex.Message);
}
}


- event handler.

No comments: