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?
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.