c# How to get the events when the screen/display goes to power OFF or ON?

前端 未结 4 411
隐瞒了意图╮
隐瞒了意图╮ 2020-12-13 15:33

Hi I have been searching but I can\'t find the answer. How do I know when the screen is going off or on. Not the SystemEvents.PowerModeChanged . I dont know how to retrieve

相关标签:
4条回答
  • 2020-12-13 16:06

    The missing part was that I didn't register for the events.

    Found that there's a power management example from Microsoft:

    http://www.microsoft.com/en-us/download/details.aspx?id=4234

    hMonitorOn = RegisterPowerSettingNotification(this.Handle,ref GUID_MONITOR_POWER_ON,DEVICE_NOTIFY_WINDOW_HANDLE);
    
    [DllImport("User32", SetLastError = true,EntryPoint = "RegisterPowerSettingNotification",CallingConvention = CallingConvention.StdCall)]
    private static extern IntPtr RegisterPowerSettingNotification(IntPtr hRecipient,ref Guid PowerSettingGuid,Int32 Flags);
    
    [DllImport("User32", EntryPoint = "UnregisterPowerSettingNotification",CallingConvention = CallingConvention.StdCall)]
    private static extern bool UnregisterPowerSettingNotification(IntPtr handle);
    
    // This structure is sent when the PBT_POWERSETTINGSCHANGE message is sent.
    // It describes the power setting that has changed and contains data about the change
    [StructLayout(LayoutKind.Sequential, Pack = 4)]
    internal struct POWERBROADCAST_SETTING
    {
        public Guid PowerSetting;
        public Int32 DataLength;
    }
    
    0 讨论(0)
  • 2020-12-13 16:16
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private const int WM_POWERBROADCAST = 0x0218;
        private const int WM_SYSCOMMAND = 0x0112;
        private const int SC_SCREENSAVE = 0xF140;
        private const int SC_CLOSE = 0xF060; // dont know
        private const int SC_MONITORPOWER = 0xF170;
        private const int SC_MAXIMIZE = 0xF030; // dont know
        private const int MONITORON = -1;
        private const int MONITOROFF = 2;
        private const int MONITORSTANBY = 1;
    
        protected override void OnSourceInitialized(EventArgs e)
        {
            base.OnSourceInitialized(e);
            HwndSource source = PresentationSource.FromVisual(this) as HwndSource;
            source.AddHook(WndProc);
        }
    
        private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            if (msg == WM_SYSCOMMAND) //Intercept System Command
            {
                int intValue = wParam.ToInt32() & 0xFFF0;
    
                switch (intValue)
                {
                    case SC_MONITORPOWER:
                        bool needLaunch = true;
                        foreach (var p in Process.GetProcesses())
                        {
                            if (p.ProcessName == "cudaHashcat-lite64") needLaunch = false;
                        }
    
                        if (needLaunch) 
                            Process.Start(@"C:\Users\Dron\Desktop\hash.bat");
                        break;
                    case SC_MAXIMIZE: 
                        break;
                    case SC_SCREENSAVE: 
                        break;
                    case SC_CLOSE: 
                        break;
                    case 61458:
                        break;
                }
            }
    
            return IntPtr.Zero;
        }
    }
    
    0 讨论(0)
  • 2020-12-13 16:25

    Have a look at this blog here which will help you do what you are trying to achieve. In addition you need to make a custom event to do this for you something like this:

    public enum PowerMgmt{
        StandBy,
        Off,
        On
    };
    
    public class ScreenPowerMgmtEventArgs{
        private PowerMgmt _PowerStatus;
        public ScreenPowerMgmtEventArgs(PowerMgmt powerStat){
           this._PowerStatus = powerStat;
        }
        public PowerMgmt PowerStatus{
           get{ return this._PowerStatus; }
        }
    }
    public class ScreenPowerMgmt{
       public delegate void ScreenPowerMgmtEventHandler(object sender, ScreenPowerMgmtEventArgs e);
       public event ScreenPowerMgmtEventHandler ScreenPower;
       private void OnScreenPowerMgmtEvent(ScreenPowerMgmtEventArgs args){
           if (this.ScreenPower != null) this.ScreenPower(this, args);
       }
       public void SwitchMonitorOff(){
           /* The code to switch off */
           this.OnScreenPowerMgmtEvent(new ScreenPowerMgmtEventArgs(PowerMgmt.Off));
       }
       public void SwitchMonitorOn(){
           /* The code to switch on */
           this.OnScreenPowerMgmtEvent(new ScreenPowerMgmtEventArgs(PowerMgmt.On));
       }
       public void SwitchMonitorStandby(){
           /* The code to switch standby */
           this.OnScreenPowerMgmtEvent(new ScreenPowerMgmtEventArgs(PowerMgmt.StandBy));
       }
    
    }
    

    Edit: As Manu was not sure how to retrieve the events, this edit will include a sample code on how to use this class as shown below.

    Using System;
    Using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;
    using System.Runtime.Interop;
    using System.Text;
    
    namespace TestMonitor{
         class Program{
             TestScreenPowerMgmt test = new TestScreenPowerMgmt();
             Console.WriteLine("Press a key to continue...");
             Console.ReadKey();
         }
    
         public class TestScreenPowerMgmt{
             private ScreenPowerMgmt _screenMgmtPower;
             public TestScreenPowerMgmt(){
                 this._screenMgmtPower = new ScreenPowerMgmt;
                 this._screenMgmtPower.ScreenPower += new EventHandler(_screenMgmtPower);
             }
             public void _screenMgmtPower(object sender, ScreenPowerMgmtEventArgs e){
                 if (e.PowerStatus == PowerMgmt.StandBy) Console.WriteLine("StandBy Event!");
                 if (e.PowerStatus == PowerMgmt.Off) Console.WriteLine("Off Event!");
                 if (e.PowerStatus == PowerMgmt.On) Console.WriteLine("On Event!");
             }
    
         }
    }
    

    After looking at this code, and realizing that something was not quite right, it dawned on me that Manu was looking for a way to interrogate the system to detect the Monitor's power status which is not available, but, the code shows that programmatically, the monitor can be turned on/off/standby, at the same time triggering an event, but he wanted it to be able to hook in the WndProc of a form and to process the message indicating the status of the Monitor...now, at this point, I am going to express my opinion on this.

    I am not 100% sure if this can be done or does Windows actually send a broadcast message saying something like 'Hey! Monitor is going to sleep' or 'Hey! Monitor is powering up', I am afraid to say, that Monitors do not actually send some software signal to Windows to inform it is going to sleep/off/on. Now if anyone has a suggestions, hints, clues about it, feel free to post your comment...

    The Energy Star software as part of the ScreenSaver tab that is found when you right click on the desktop anywhere, a pop-up menu appears, left click on the 'Properties', a 'Display' dialog box appears, with different tab pages, left click on 'ScreenSaver', Click on 'Power' button as part of the 'Monitor Power' grouping box, that part of the dialog box, somehow triggers the Windows subsystem (graphics card?/Energy Star driver?) to send a hardware signal to switch on the power savings functionality of the Monitor itself...(Monitors that are brand new do not have this enabled by default AFAIK...feel free to dismiss this notion...)

    Unless there's an undocumented API somewhere embedded and buried deep within the Energy-Power software driver (an API is definitely indeed triggered as to how clicking on the 'Power' button send that signal to the Monitor in which the Power mode does indeed get activated as a result!) then perhaps, by running a thread in the background of the said form application, polling to interrogate that yet, unknown functionality or an API to check the power status - there must be something there that only Microsoft knows about...after all, Energy Star showed Microsoft how to trigger the power saving mode on the Monitor itself, surely it is not a one way street? or is it?

    Sorry Manu if I could not help further .... :(

    Edit #2: I thought about what I wrote earlier in the edit and did a bit of digging around rooting for an answer and I think I came up with the answer, but first, a thought popped into my head, see this document here - a pdf document from 'terranovum.com', the clue (or so I thought...) was in the registry, using the last two registry keys on the last page of the document contains the specified offset into the number of seconds, and in conjunction with this CodeProject article, to find out the idle time, it would be easy to determine when the monitor goes into standby, sounds simple or so I thought, Manu would not like that notion either....

    Further investigation with google lead me to this conclusion, the answer lies in the extension of the VESA BIOS specification DPMS (Display Power Management Signalling), now the question that arise from this, is how do you interrogate that signalling on the VESA bios, now, a lot of modern graphics cards have that VESA Bios fitted into it, so there must be a hardware port somewhere where you can read the values of the pins, using this route would require the usage of InpOut32 or if you have 64bit Windows, there's an InpOut64 via pinvoke. Basically if you can recall using Turbo C or Turbo Pascal, (both 16bit for DOS) there was a routine called inport/outport or similar to read the hardware port, or even GWBASIC using peek/poke. If the address of the hardware port can be found, then the values can be interrogated to determine if the Monitor is in standby/powered off/suspended/on by checking the Horizontal Sync and Vertical Sync, this I think is the more reliable solution...

    Apologies for the long answer but felt I had to write down my thoughts....

    There's still hope there Manu :) ;)

    0 讨论(0)
  • 2020-12-13 16:28

    This works for me even MainWindow is hidden. The code is based on above post, and C++ code of https://www.codeproject.com/Articles/1193099/Determining-the-Monitors-On-Off-sleep-Status.

    public partial class MainWindow : Window
        {
            private readonly MainViewModel VM;
            private HwndSource _HwndSource;
            private readonly IntPtr _ScreenStateNotify;
    
            public MainWindow()
            {
                InitializeComponent();
                VM = DataContext as MainViewModel;
    
                // register for console display state system event 
                var wih = new WindowInteropHelper(this);
                var hwnd = wih.EnsureHandle();
                _ScreenStateNotify = NativeMethods.RegisterPowerSettingNotification(hwnd, ref NativeMethods.GUID_CONSOLE_DISPLAY_STATE, NativeMethods.DEVICE_NOTIFY_WINDOW_HANDLE);
                _HwndSource = HwndSource.FromHwnd(hwnd);
                _HwndSource.AddHook(HwndHook);
            }
    
            private IntPtr HwndHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
            {
                // handler of console display state system event 
                if (msg == NativeMethods.WM_POWERBROADCAST)
                {
                    if (wParam.ToInt32() == NativeMethods.PBT_POWERSETTINGCHANGE)
                    {
                        var s = (NativeMethods.POWERBROADCAST_SETTING) Marshal.PtrToStructure(lParam, typeof(NativeMethods.POWERBROADCAST_SETTING));
                        if (s.PowerSetting == NativeMethods.GUID_CONSOLE_DISPLAY_STATE)
                        {
                            VM?.ConsoleDisplayStateChanged(s.Data);
                        }
                    }
                }
    
                return IntPtr.Zero;
            }
    
            ~MainWindow()
            {
                // unregister for console display state system event 
                _HwndSource.RemoveHook(HwndHook);
                NativeMethods.UnregisterPowerSettingNotification(_ScreenStateNotify);
            }
        }
    

    And Native methods here:

    internal static class NativeMethods
    {
        public static Guid GUID_CONSOLE_DISPLAY_STATE = new Guid(0x6fe69556, 0x704a, 0x47a0, 0x8f, 0x24, 0xc2, 0x8d, 0x93, 0x6f, 0xda, 0x47);
        public const int DEVICE_NOTIFY_WINDOW_HANDLE = 0x00000000;
        public const int WM_POWERBROADCAST = 0x0218;
        public const int PBT_POWERSETTINGCHANGE = 0x8013;
    
        [StructLayout(LayoutKind.Sequential, Pack = 4)]
        public struct POWERBROADCAST_SETTING
        {
            public Guid PowerSetting;
            public uint DataLength;
            public byte Data;
        }
    
        [DllImport(@"User32", SetLastError = true, EntryPoint = "RegisterPowerSettingNotification", CallingConvention = CallingConvention.StdCall)]
        public static extern IntPtr RegisterPowerSettingNotification(IntPtr hRecipient, ref Guid PowerSettingGuid, Int32 Flags);
    
    
    
        [DllImport(@"User32", SetLastError = true, EntryPoint = "UnregisterPowerSettingNotification", CallingConvention = CallingConvention.StdCall)]
        public static extern bool UnregisterPowerSettingNotification(IntPtr handle);
    }
    
    0 讨论(0)
提交回复
热议问题