|
| 1 | +// This Source Code Form is subject to the terms of the Mozilla Public |
| 2 | +// License, v. 2.0. If a copy of the MPL was not distributed with this |
| 3 | +// file, You can obtain one at http://mozilla.org/MPL/2.0/. |
| 4 | + |
| 5 | +using System; |
| 6 | +using System.Runtime.InteropServices; |
| 7 | +using System.Windows.Forms; |
| 8 | + |
| 9 | +namespace WinDynamicDesktop.COM |
| 10 | +{ |
| 11 | + [StructLayout(LayoutKind.Sequential)] |
| 12 | + public struct POWERBROADCAST_SETTING |
| 13 | + { |
| 14 | + public Guid PowerSetting; |
| 15 | + public int DataLength; |
| 16 | + // Variable length data follows |
| 17 | + } |
| 18 | + |
| 19 | + internal class PowerSetting |
| 20 | + { |
| 21 | + private static readonly Guid GUID_CONSOLE_DISPLAY_STATE = |
| 22 | + new Guid("6fe69556-704a-47a0-8f24-c28d936fda47"); |
| 23 | + |
| 24 | + private static IntPtr hPowerNotify; |
| 25 | + private static int? lastDisplayState = null; |
| 26 | + |
| 27 | + [DllImport("user32.dll")] |
| 28 | + private static extern IntPtr RegisterPowerSettingNotification( |
| 29 | + IntPtr hRecipient, ref Guid PowerSettingGuid, int Flags); |
| 30 | + |
| 31 | + [DllImport("user32.dll")] |
| 32 | + private static extern bool UnregisterPowerSettingNotification(IntPtr Handle); |
| 33 | + |
| 34 | + public static void RegisterWindow(IntPtr windowHandle) |
| 35 | + { |
| 36 | + Guid guid = GUID_CONSOLE_DISPLAY_STATE; |
| 37 | + hPowerNotify = RegisterPowerSettingNotification(windowHandle, ref guid, 0); |
| 38 | + |
| 39 | + if (hPowerNotify != IntPtr.Zero) |
| 40 | + { |
| 41 | + Application.ApplicationExit += (object sender, EventArgs e) => |
| 42 | + { |
| 43 | + UnregisterPowerSettingNotification(hPowerNotify); |
| 44 | + }; |
| 45 | + } |
| 46 | + else |
| 47 | + { |
| 48 | + LoggingHandler.LogMessage("Failed to register for power notifications"); |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + public static bool IsExitingStandby(nint msgPtr) |
| 53 | + { |
| 54 | + var powerSetting = Marshal.PtrToStructure<POWERBROADCAST_SETTING>(msgPtr); |
| 55 | + |
| 56 | + if (powerSetting.PowerSetting.Equals(GUID_CONSOLE_DISPLAY_STATE)) |
| 57 | + { |
| 58 | + IntPtr dataPtr = new(msgPtr.ToInt64() + Marshal.SizeOf<POWERBROADCAST_SETTING>()); |
| 59 | + int displayState = Marshal.ReadInt32(dataPtr); |
| 60 | + |
| 61 | + bool stateChanged = lastDisplayState.HasValue && lastDisplayState.Value != displayState; |
| 62 | + lastDisplayState = displayState; |
| 63 | + |
| 64 | + // If state changed and display is turning on, assume we are exiting standby |
| 65 | + return stateChanged && displayState == 1; |
| 66 | + } |
| 67 | + |
| 68 | + return false; |
| 69 | + } |
| 70 | + } |
| 71 | +} |
0 commit comments