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.
This commit is contained in:
2025-06-11 20:39:08 +03:00
parent ddbd8092a8
commit 0c0c72be9f

View File

@@ -8,6 +8,8 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.Linq; using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Timers; using System.Timers;
@@ -147,25 +149,63 @@ public class Updater : IDisposable
try try
{ {
var spotifyProcesses = Process.GetProcessesByName("Spotify"); var spotifyProcesses = Process.GetProcessesByName("Spotify");
var trackTitles = new List<string>();
foreach (var process in spotifyProcesses) foreach (var process in spotifyProcesses)
{ {
if (!string.IsNullOrEmpty(process.MainWindowTitle) && EnumWindows((hWnd, lParam) =>
process.MainWindowTitle != "Spotify" &&
process.MainWindowTitle != "Spotify Premium" &&
process.MainWindowTitle != "Spotify Free")
{ {
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) catch (Exception ex)
{ {
PluginLog.Debug($"Error getting Spotify track: {ex.Message}"); PluginLog.Debug($"Error getting Spotify track: {ex.Message}");
} }
return null; 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) private bool MediaActivitiesEqual(MediaActivity? a, MediaActivity? b)
{ {
if (a == null && b == null) return true; if (a == null && b == null) return true;