tags:

views:

152

answers:

3

Hi. I have develop a program which turns off the monitor by standard sendmassage api call:

    public int WM_SYSCOMMAND = 0x0112;
    public int SC_MONITORPOWER = 0xF170;
    const int HWND_BROADCAST  = 0xFFFF;
    SendMessage(-1, WM_SYSCOMMAND, SC_MONITORPOWER, 2);

My question is I dont want it to be a windows form, but a windows service instead... The sendmessage doesnt not in a windows service. How can I get it to work?

Regards, Christian

A: 

You can use GetDesktopWindow method and send the message to that window. Or you can use FindWindow and FindWindowEx methods to get the currently active window and send message there. Or you can add a reference to System.Windows.Forms in your service and instantiate a Form object and use that handle to send the message.

danish
I already tried the last solution, adding a form, but with no result: Form f = new Form(); SendMessage(f.Handle.ToInt32(), WM_SYSCOMMAND, SC_MONITORPOWER, 2);
Christian
SendMessage(GetDesktopWindow().ToInt32(), WM_SYSCOMMAND, SC_MONITORPOWER, 2); Doesnt work either.....
Christian
1. Last method is not a best practice (Adding form reference).2. GetDesktopWindow: Might have some thing to do with the security permission in your system.Try using FindWindow. If that doesn't works either, I am clueless then.
danish
+1  A: 

Using HWND_BROADCAST / -1 is so wrong I don't even know where to begin, see this blog post for details

If for whatever reason you can't create a window, you could try to PInvoke the DefWindowProc function directly

Are you even sure it is possible to do this from a service? You might have to call CreateProcessAsUser and start a helper app

Anders
A: 

Hmm, ok.. No, im not sure at all if this is possible. I hoped to find out in this forum...

chrass