From 0c0c72be9ff7b29a3d9c4a6e94927ae9948db108 Mon Sep 17 00:00:00 2001 From: Administrator Date: Wed, 11 Jun 2025 20:39:08 +0300 Subject: [PATCH] Enhance Spotify track retrieval in Updater.cs Updated `Updater.cs` to improve functionality for retrieving the currently playing track in Spotify. Added new methods for window title retrieval and utilized the `EnumWindows` function to filter and identify relevant Spotify track titles. Included P/Invoke declarations for Windows API functions to support these enhancements, along with a new method `GetWindowTitle` for better code organization. --- SpotifyHonorific/Updaters/Updater.cs | 54 ++++++++++++++++++++++++---- 1 file changed, 47 insertions(+), 7 deletions(-) diff --git a/SpotifyHonorific/Updaters/Updater.cs b/SpotifyHonorific/Updaters/Updater.cs index 2fd1a18..768f664 100644 --- a/SpotifyHonorific/Updaters/Updater.cs +++ b/SpotifyHonorific/Updaters/Updater.cs @@ -8,6 +8,8 @@ using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; +using System.Runtime.InteropServices; +using System.Text; using System.Threading.Tasks; using System.Timers; @@ -147,25 +149,63 @@ public class Updater : IDisposable try { var spotifyProcesses = Process.GetProcessesByName("Spotify"); + var trackTitles = new List(); + foreach (var process in spotifyProcesses) { - if (!string.IsNullOrEmpty(process.MainWindowTitle) && - process.MainWindowTitle != "Spotify" && - process.MainWindowTitle != "Spotify Premium" && - process.MainWindowTitle != "Spotify Free") + EnumWindows((hWnd, lParam) => { - return process.MainWindowTitle; - } + uint processId; + GetWindowThreadProcessId(hWnd, out processId); + + if (processId == process.Id) + { + var title = GetWindowTitle(hWnd); + if (!string.IsNullOrEmpty(title) && + title != "Spotify" && + title != "Spotify Premium" && + title != "Spotify Free" && + title.Contains(" - ")) + { + trackTitles.Add(title); + } + } + return true; + }, IntPtr.Zero); } + + return trackTitles.OrderByDescending(t => t.Length).FirstOrDefault(); } catch (Exception ex) { PluginLog.Debug($"Error getting Spotify track: {ex.Message}"); } - return null; } + private string GetWindowTitle(IntPtr hWnd) + { + const int nChars = 256; + var buff = new StringBuilder(nChars); + if (GetWindowTextW(hWnd, buff, nChars) > 0) + { + return buff.ToString(); + } + return string.Empty; + } + + + [DllImport("user32.dll")] + private static extern bool EnumWindows(EnumWindowsProc enumProc, IntPtr lParam); + + [DllImport("user32.dll")] + private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId); + + [DllImport("user32.dll", CharSet = CharSet.Unicode)] + private static extern int GetWindowTextW(IntPtr hWnd, StringBuilder text, int count); + + private delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam); + private bool MediaActivitiesEqual(MediaActivity? a, MediaActivity? b) { if (a == null && b == null) return true;