在c#中将显示发送到睡眠模式

时间:2010-08-29 11:05:53

标签: c#

这是一个标准的Windows功能,显示器在配置的时间后进入睡眠模式。是否有可能立即从Windows 7中的c#.net应用程序将显示器发送到睡眠模式?我已经尝试了一件我发现的东西,但它对我不起作用。

[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似乎有一个有效值,但ret始终为0.

thx,kopi_b

3 个答案:

答案 0 :(得分:8)

这在WinForms应用程序中运行良好:

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);
    }
}

问题似乎来自GetDesktopWindow函数。

答案 1 :(得分:4)

您需要使用HWND_BROADCAST而不是桌面窗口句柄来确保显示器关机:

private const int HWND_BROADCAST = 0xFFFF;

var ret = SendMessage((IntPtr)HWND_BROADCAST, WM_SYSCOMMAND, (IntPtr)SC_MONITORPOWER, (IntPtr)MONITOR_OFF);

答案 2 :(得分:0)

我有Visual Studio 2010和Windows 7,并创建了一个带有“睡眠”和“休眠”按钮的Windows窗体应用程序。以下对我有用:

private void Sleep_Click(object sender, EventArgs e)
{
    bool retVal = Application.SetSuspendState(PowerState.Suspend, false, false);

    if (retVal == false)
        MessageBox.Show("Could not suspend the system.");
}

private void Hibernate_Click(object sender, EventArgs e)
{
    bool retVal = Application.SetSuspendState(PowerState.Hibernate, false, false);

    if (retVal == false)
        MessageBox.Show("Could not hybernate the system.");
}

我发现了here