using CoreAudio; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace FocusVolumeControl { internal class AudioHelper { ActiveAudioSessionWrapper GetSessionForProcess(Process process) { var deviceEnumerator = new MMDeviceEnumerator(Guid.NewGuid()); using var device = deviceEnumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia); using var manager = device.AudioSessionManager2; var sessions = manager.Sessions; foreach (var session in sessions) { var audioProcess = Process.GetProcessById((int)session.ProcessID); if (session.ProcessID == process.Id || audioProcess?.ProcessName == process.ProcessName) { var displayName = audioProcess.MainModule.FileVersionInfo.FileDescription; var path = audioProcess.MainModule.FileName; return new ActiveAudioSessionWrapper() { DisplayName = displayName, ExecutablePath = path, Volume = session.SimpleAudioVolume }; } } return null; } internal ActiveAudioSessionWrapper GetActiveSession() { const int nChars = 256; IntPtr handle = IntPtr.Zero; StringBuilder Buff = new StringBuilder(nChars); handle = Native.GetForegroundWindow(); if (handle == IntPtr.Zero) { //todo: return system or something like that? return null; } var tid = Native.GetWindowThreadProcessId(handle, out var pid); var process = Process.GetProcessById(pid); return GetSessionForProcess(process); } } }