Last active
August 16, 2025 21:00
-
-
Save BitesizedLion/2a230cab5985089493779708c9ac4612 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Runtime.InteropServices; | |
using NAudio.CoreAudioApi; | |
using NAudio.CoreAudioApi.Interfaces; | |
namespace PauseOnDisconnect | |
{ | |
internal class Program | |
{ | |
public static bool Active { get; private set; } = true; | |
#pragma warning disable CS8618, CS8622 | |
static NotifyIcon trayIcon; | |
static void Main(string[] args) | |
{ | |
trayIcon = new NotifyIcon() | |
{ | |
Icon = SystemIcons.WinLogo, | |
Text = "pauseondisconnect", | |
Visible = true | |
}; | |
trayIcon.Click += ToggleApp; | |
MMDeviceEnumerator enumerator = new(); | |
enumerator.RegisterEndpointNotificationCallback(new AudioNotifier()); | |
Application.Run(); | |
} | |
private static void ToggleApp(object sender, EventArgs e) | |
{ | |
Console.WriteLine("hello"); | |
Active = !Active; | |
trayIcon.Icon = Active ? SystemIcons.WinLogo : SystemIcons.Warning; | |
} | |
} | |
internal class AudioNotifier : IMMNotificationClient | |
{ | |
[DllImport("user32.dll")] | |
static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, UIntPtr dwExtraInfo); | |
public const int KEYEVENTF_KEYUP = 0x0002; | |
public const byte VK_MEDIA_PLAY_PAUSE = 0xB3; | |
public void OnDeviceStateChanged(string deviceId, DeviceState newState) | |
{ | |
Console.WriteLine(deviceId, newState); | |
} | |
public void OnDeviceAdded(string pwstrDeviceId) { } | |
public void OnDeviceRemoved(string deviceId) { } | |
public void OnDefaultDeviceChanged(DataFlow flow, Role role, string defaultDeviceId) { | |
if (!Program.Active) return; | |
if (flow == DataFlow.Render && role == Role.Console) // I'll just do like this and hope it works. | |
{ | |
Console.WriteLine("flow: {0}, role: {1}, id: {2}", flow, role, defaultDeviceId); | |
// i tried using GSMTC but fuck winrt and all that bullshit | |
keybd_event(VK_MEDIA_PLAY_PAUSE, 0, 0, UIntPtr.Zero); | |
keybd_event(VK_MEDIA_PLAY_PAUSE, 0, KEYEVENTF_KEYUP, UIntPtr.Zero); | |
} | |
} | |
public void OnPropertyValueChanged(string pwstrDeviceId, PropertyKey key) { } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment