From db15380fcf89c51f80286ed6cf7b35bbc581396d Mon Sep 17 00:00:00 2001 From: Yu Leng Date: Wed, 10 Dec 2025 10:15:40 +0800 Subject: [PATCH] Improve WMI monitor name extraction using length property Refactor GetUserFriendlyName to use UserFriendlyNameLength for accurate string extraction from the WMI UserFriendlyName buffer. This ensures only valid characters are included, improving reliability when parsing monitor names. --- .../PowerDisplay.Lib/Drivers/WMI/WmiController.cs | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/modules/powerdisplay/PowerDisplay.Lib/Drivers/WMI/WmiController.cs b/src/modules/powerdisplay/PowerDisplay.Lib/Drivers/WMI/WmiController.cs index d616eb2312..c68487452c 100644 --- a/src/modules/powerdisplay/PowerDisplay.Lib/Drivers/WMI/WmiController.cs +++ b/src/modules/powerdisplay/PowerDisplay.Lib/Drivers/WMI/WmiController.cs @@ -405,20 +405,22 @@ namespace PowerDisplay.Common.Drivers.WMI } /// - /// Get user-friendly name from WMI object + /// Get user-friendly name from WMI object. + /// WmiMonitorID returns UserFriendlyName as a fixed-size uint16 array buffer, + /// with UserFriendlyNameLength indicating the actual character count. /// private static string? GetUserFriendlyName(WmiObject monitorObject) { try { - // WmiLight returns arrays as object arrays - var userFriendlyNameObj = monitorObject.GetPropertyValue("UserFriendlyName"); + var userFriendlyName = monitorObject.GetPropertyValue("UserFriendlyName"); + var nameLength = monitorObject.GetPropertyValue("UserFriendlyNameLength"); - if (userFriendlyNameObj is ushort[] userFriendlyName && userFriendlyName.Length > 0) + if (userFriendlyName != null && nameLength > 0 && nameLength <= userFriendlyName.Length) { - // Convert UINT16 array to string + // Use UserFriendlyNameLength to extract only valid characters var chars = userFriendlyName - .Where(c => c != 0) + .Take(nameLength) .Select(c => (char)c) .ToArray(); @@ -430,7 +432,6 @@ namespace PowerDisplay.Common.Drivers.WMI } catch (Exception ex) { - // Ignore conversion errors Logger.LogDebug($"Failed to parse UserFriendlyName: {ex.Message}"); }