views:

127

answers:

3

I have written a Windows service which should turn the display OFF when certain conditions occur. The code I am using is :

private const int MONITOR_OFF = 2;
SendMessage(GetDesktopWindow().ToInt32(), 
   WM_SYSCOMMAND, SC_MONITORPOWER, MONITOR_OFF);

This same code works from a Windows application but when executed from Windows service, nothing happens. There is no exception either and Marshal.GetLastWin32Error() also returns 0.

Any ideas on what I might be missing?

+1  A: 

You can try editing the properties of the service, in the services management utility to allow desktop interaction.

Josh Pearce
Thanks Josh but that did not help resolve the issue
Sanket
Well, you can go to the same properties screen, and instead choose to run as an actual user ans put in your credentials.
Josh Pearce
+4  A: 

Because a service has no default access to the desktop, so your call to GetDesktopWindow() is returning something other than you expect; you then blindly convert that to an Int32 and use that as a window handle target of SendMessage(). Since the recipient probably isn't a valid window, it doesn't do anything.

Ken White
A: 

Services run in their own virtual desktop space (they can even have their own user profile space.) It is part of the security model built into windows. Your best bet would be to have a service that runs in the background and a user mode client that runs in the users desktop. Depending on the level of access of the user would make it possible for the user to kill the service/user mode client. But you could also query the processes to make sure the user app is still running.

Matthew Whited