2

I'm trying to detect when windows powers off/on the monitor because of display sleep settings. (Settings -> System -> Power & Sleep -> Screen)

Only way I found to do this is by listening to a SC_MONITORPOWER message but I'm experiencing a issue with this message in WPF project. I've created a hook for WndProc inside my Main view, and I'm listening to a SC_MONITORPOWER message. Problem I'm experiencing is that lParam is always "2" which means according to specs that monitor shutoff. Same value of lParam I get when monitor powers on. Any idea what I may be doing wrong

Here is the code:

    protected override void OnSourceInitialized(EventArgs e)
    {
        base.OnSourceInitialized(e);
        var handle = new WindowInteropHelper(this).Handle;

        HwndSource.FromHwnd(handle)?.AddHook(WndProc);
    }

    private static IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
    {
        // WM_SYSCOMMAND
        if (msg != 0x0112)
        {
            return IntPtr.Zero;
        }

        var subCode = wParam.ToInt32() & 0xFFF0;

        // SC_MONITORPOWER
        if (subCode != 0xF170)
        {
            return IntPtr.Zero;
        }

        var param = lParam.ToInt32();

        switch (param)
        {
            case -1:
                // Display is powering on
                return IntPtr.Zero;
            case 1:
                // Display is going to low power
                return IntPtr.Zero;
            case 2:
                // I always get this case
                // Display is being shut off
                return IntPtr.Zero;
        }

        return IntPtr.Zero;
}

Maybe there is another solution in WPF to detect when monitor goes off/on by windows display sleep settings?

OvidiuS
  • 21
  • 2
  • related: https://stackoverflow.com/questions/203355/is-there-any-way-to-detect-the-monitor-state-in-windows-on-or-off but you might hope things improved since 2008... – rene Apr 19 '18 at 07:11
  • It's more usual to care about the computer going to sleep rather than the monitor. Why do you care about the monitor? – Andy Apr 19 '18 at 08:05
  • I think I've got some code checks for the computer sleeping or user switching BTW. – Andy Apr 19 '18 at 08:06

0 Answers0