I needed something similar (getting the currently playing media from apps like spotify or any other mediaplayer that utilizes SystemMediaTransportControls and found the way for it.
according to this link:
https://learn.microsoft.com/en-us/windows/apps/desktop/modernize/desktop-to-uwp-enhance
if you are using .net 6 or later you need to set your target pltform to windows10.0.17763.0 or just modify your project file:
<TargetFramework>net7.0-windows10.0.17763.0</TargetFramework>
and if you are using .NET Framework 4.6+ or .NET Core 3.0+ you must install the Microsoft.Windows.SDK.Contracts
nuget package.
then you can add using Windows.Media.Control;
and here's a sample code (it isn't well-written but you can see how to use the API) that displays your currently playing media (also utilizes events to display new media and media playback status)
using System;
using System.Security.Cryptography;
using System.Threading.Tasks;
using Windows.Media.Control;
namespace TestGetCurrentMedia
{
internal class Program
{
public static async Task Main(string[] args)
{
var gsmtcsm = await GetSystemMediaTransportControlsSessionManager();
Gsmtcsm_CurrentSessionChanged(gsmtcsm, null);
gsmtcsm.CurrentSessionChanged += Gsmtcsm_CurrentSessionChanged;
Console.ReadLine();
}
static string LastString = "";
private static async void Gsmtcsm_CurrentSessionChanged(GlobalSystemMediaTransportControlsSessionManager sender, CurrentSessionChangedEventArgs args)
{
var s = sender.GetCurrentSession();
if (s != null)
{
s.MediaPropertiesChanged += S_MediaPropertiesChanged;
S_MediaPropertiesChanged(s, null);
s.PlaybackInfoChanged += S_PlaybackInfoChanged;
S_PlaybackInfoChanged(s, null);
}
//GC.Collect();
}
private static void S_PlaybackInfoChanged(GlobalSystemMediaTransportControlsSession sender, PlaybackInfoChangedEventArgs args)
{
GlobalSystemMediaTransportControlsSessionPlaybackInfo playbackInfo = sender.GetPlaybackInfo();
Console.WriteLine(LastString + " => " + playbackInfo.PlaybackStatus);
}
private static async void S_MediaPropertiesChanged(GlobalSystemMediaTransportControlsSession sender, MediaPropertiesChangedEventArgs args)
{
GlobalSystemMediaTransportControlsSessionMediaProperties mediaProperties = await sender.TryGetMediaPropertiesAsync();
if (mediaProperties != null)
{
string Curr = ($"{mediaProperties.Artist} - {mediaProperties.Title} - {mediaProperties.TrackNumber}");
if (!Curr.Equals(LastString))
{
//Console.WriteLine(Curr);
LastString = Curr;
S_PlaybackInfoChanged(sender, null);
}
}
}
private static async Task<GlobalSystemMediaTransportControlsSessionManager> GetSystemMediaTransportControlsSessionManager() =>
await GlobalSystemMediaTransportControlsSessionManager.RequestAsync();
}
}