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
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With