传送一台显示器进入睡眠状态

时间:2019-08-07 12:10:42

标签: c# windows winforms

我有多个监视器,但通常我不需要所有监视器。因此,当鼠标在屏幕上一段时间没有移动时,我希望将它们一个一地发送到睡眠模式。所以我的问题是如何让一台显示器进入睡眠状态?

我已经尝试过了,但是没有运气:https://www.codeproject.com/Articles/12794/Complete-Guide-on-How-To-Turn-A-Monitor-On-Off-Sta 它将始终使所有屏幕进入睡眠状态。

private void Button1_Click(object sender, EventArgs e)
{
    var hWnd = NativeMethods.FindWindow(this.Text);

    NativeMethods.MonitorOff(hWnd);
    Thread.Sleep(5000);
    NativeMethods.MonitorOn(hWnd);
}

private static class NativeMethods
{
    internal static void MonitorOn(IntPtr? hWnd = null)
    {
        SendMessage(hWnd ?? HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, (IntPtr)MONITOR_ON);
    }

    internal static void MonitorOff(IntPtr? hWnd = null)
    {
        SendMessage(hWnd ?? HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, (IntPtr)MONITOR_OFF);
    }

    internal static IntPtr FindWindow(string lpWindowName)
    {
        return FindWindow(null, lpWindowName);
    }

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

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

    [DllImport("user32.dll", SetLastError = true)]
    static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

    private static int MONITOR_ON = -1;
    private static int MONITOR_OFF = 2;
    private static int MONITOR_STANBY = 1;

    /// <summary>
    /// the message is sent to all top-level windows in the system
    /// </summary>
    private static IntPtr HWND_BROADCAST = new IntPtr(0xffff);
    /// <summary>
    /// the message is sent to one top-level window in the system
    /// </summary>
    private static IntPtr HWND_TOPMOST = new IntPtr(-1);

    private static UInt32 WM_SYSCOMMAND = 0x0112;
    private static IntPtr SC_MONITORPOWER = new IntPtr(0xF170);
}

1 个答案:

答案 0 :(得分:0)

从问题的表达方式来看,您实际上并不想让屏幕进入睡眠状态,而只是想停止向屏幕发送信号。这取决于您的设置。
如果您的设置中每个监视器在PC上都有其自己的端口,则只需关闭相应的HDMI / VGA / DP端口即可。请注意,这确实意味着仅通过将鼠标指针移到那里就可能无法唤醒屏幕(或在这种情况下,恢复发送数据)。
如果您的设置使PC某种程度上没有每个屏幕的端口,则可能无法实现。

长话短说,想要的睡眠是不可能的,只能切断信号。