diff --git a/LightBulb.PlatformInterop/Internal/WndProcMessage.cs b/LightBulb.PlatformInterop/Internal/WndProcMessage.cs index 6a81ca1..8663a6c 100644 --- a/LightBulb.PlatformInterop/Internal/WndProcMessage.cs +++ b/LightBulb.PlatformInterop/Internal/WndProcMessage.cs @@ -1,13 +1,14 @@ -using System; -using System.Runtime.InteropServices; +using System.Runtime.InteropServices; namespace LightBulb.PlatformInterop.Internal; internal readonly record struct WndProcMessage(uint Id, nint WParam, nint LParam) { - public T GetLParam() => - (T?)Marshal.PtrToStructure(LParam, typeof(T)) - ?? throw new InvalidOperationException( - $"Failed to deserialize WndProc message's lParam to {typeof(T)}." - ); + public T? TryGetLParam() + where T : struct => + // If LParam is zero, marshaling will fail with null reference exception + // https://github.com/Tyrrrz/LightBulb/issues/275 + LParam != 0 + ? Marshal.PtrToStructure(LParam) + : default(T?); } diff --git a/LightBulb.PlatformInterop/PowerSettingNotification.cs b/LightBulb.PlatformInterop/PowerSettingNotification.cs index e7971f7..7fb185d 100644 --- a/LightBulb.PlatformInterop/PowerSettingNotification.cs +++ b/LightBulb.PlatformInterop/PowerSettingNotification.cs @@ -12,7 +12,7 @@ public partial class PowerSettingNotification(nint handle, Guid powerSettingId, m => { // Filter out other power events - if (m.GetLParam().PowerSettingId != powerSettingId) + if (m.TryGetLParam()?.PowerSettingId != powerSettingId) return; callback();