Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

send display to sleep mode in c#

Tags:

c#

it's a standard windows function that the display goes into sleep mode after the configured time. is it somehow possible to send the display into sleep mode immediately from a c# .net application in windows 7? i've already tried one thing i found but it didn't work for me.

[DllImport("user32.dll")]
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);

[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern IntPtr GetDesktopWindow();

private const int SC_MONITORPOWER = 0xF170;
private const UInt32 WM_SYSCOMMAND = 0x0112;
private const int MONITOR_ON = -1;
private const int MONITOR_OFF = 2;
private const int MONITOR_STANBY = 1;

public static void DisplayToSleep()
{
    var hWnd = GetDesktopWindow();
    var ret = SendMessage(hWnd , Constants.WM_SYSCOMMAND, (IntPtr)Constants.SC_MONITORPOWER, (IntPtr)Constants.MONITOR_OFF);
}

hWnd seems to have a valid value but ret is always 0.

thx, kopi_b

like image 787
kopi_b Avatar asked Aug 29 '10 11:08

kopi_b


2 Answers

This works fine in a WinForms application:

public partial class Form1 : Form
{
    private int SC_MONITORPOWER = 0xF170;
    private uint WM_SYSCOMMAND = 0x0112;

    [DllImport("user32.dll")]
    static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        SendMessage(this.Handle, WM_SYSCOMMAND, (IntPtr)SC_MONITORPOWER, (IntPtr)2);
    }
}

The problem seems to come from the GetDesktopWindow function.

like image 92
Darin Dimitrov Avatar answered Nov 01 '22 04:11

Darin Dimitrov


You need to use HWND_BROADCAST instead of the desktop window handle to ensure that the monitor powers off:

private const int HWND_BROADCAST = 0xFFFF;

var ret = SendMessage((IntPtr)HWND_BROADCAST, WM_SYSCOMMAND, (IntPtr)SC_MONITORPOWER, (IntPtr)MONITOR_OFF);
like image 20
Chris Schmich Avatar answered Nov 01 '22 03:11

Chris Schmich