0

I am creating an application that turns off the computer display via program using the following code:

private const int WM_SYSCOMMAND = 0x0112;
private const int SC_MONITORPOWER = 0xF170;

[DllImport("user32.dll")]
    private static extern int SendMessage(int hWnd, int hMsg, int wParam, int lParam);

public void turnOffMonitor(int Handle)
    {
        SendMessage(Handle, WM_SYSCOMMAND, SC_MONITORPOWER, 2);
    }

and to get the window handle i'm using the following code

[DllImport("user32.dll")]
    private static extern IntPtr GetForegroundWindow();

public static int getCurrentWindowHandle()
    {
        IntPtr hWnd = GetForegroundWindow();
        int handle = hWnd.ToInt32();
        return handle;
    }

Note: This application i am creating has no UI.

Every thing works fine when debugging it in Visual studio 2008 professional. But when i pin the exe to the task bar and click it the window handle returned is 0. So the display fails to turn off. Now, what should i do to get the window handle when launching the application from the task bar?

The Example Main Program will be like this:

static class Program
{
    private static const int WM_SYSCOMMAND = 0x0112;
private  static const int SC_MONITORPOWER = 0xF170;

[DllImport("user32.dll")]
    private static extern int SendMessage(int hWnd, int hMsg, int wParam, int lParam);

[DllImport("user32.dll")]
    private static extern IntPtr GetForegroundWindow();

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        IntPtr hWnd = GetForegroundWindow();
        int handle = hWnd.ToInt32()
        SendMessage(handle, WM_SYSCOMMAND, SC_MONITORPOWER, 2);            
    }
VJ_Koushik
  • 53
  • 7
  • try sending message to `(IntPtr)HWND_BROADCAST` instead of your UI window which don't exist. by the way `BROADCAST` is `int HWND_BROADCAST = 0xFFFF;` – bansi Aug 11 '14 at 04:53
  • nice to hear it worked for you. – bansi Aug 12 '14 at 06:11

0 Answers0