Repository navigation
Expand file tree
/
Copy pathAudioSwitcher.cpp
More file actions
668 lines (595 loc) · 24.5 KB
/
Copy pathAudioSwitcher.cpp
File metadata and controls
668 lines (595 loc) · 24.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
// AudioSwitcher - alterna a saida de audio padrao do Windows por hotkey global.
//
// App nativo Win32, sem dependencias externas. Vive na bandeja do sistema.
// Aperte a hotkey (padrao Ctrl+F1) para ciclar entre os dispositivos de saida.
//
// Build: build.bat (usa o MSVC do Visual Studio Build Tools)
#ifndef UNICODE
#define UNICODE
#endif
#include <initguid.h>
#include <windows.h>
#include <shellapi.h>
#include <shlobj.h>
#include <mmdeviceapi.h>
#include <functiondiscoverykeys_devpkey.h>
#include <string>
#include <vector>
#include <algorithm>
#pragma comment(lib, "ole32.lib")
#pragma comment(lib, "oleaut32.lib")
#pragma comment(lib, "shell32.lib")
#pragma comment(lib, "shlwapi.lib")
#pragma comment(lib, "advapi32.lib")
#pragma comment(lib, "user32.lib")
#pragma comment(lib, "propsys.lib")
#pragma comment(linker, "/SUBSYSTEM:WINDOWS")
// ---------------------------------------------------------------------------
// IPolicyConfig -- interface COM nao documentada usada para definir o
// dispositivo de audio padrao. E o mesmo mecanismo usado por NirCmd,
// SoundSwitch, AudioSwitcher, etc. Estavel no Windows 7..11.
// ---------------------------------------------------------------------------
interface DECLSPEC_UUID("f8679f50-850a-41cf-9c72-430f290290c8") IPolicyConfig;
class DECLSPEC_UUID("870af99c-171d-4f9e-af0d-e63df40c2bc9") CPolicyConfigClient;
interface IPolicyConfig : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE GetMixFormat(PCWSTR, WAVEFORMATEX**) = 0;
virtual HRESULT STDMETHODCALLTYPE GetDeviceFormat(PCWSTR, INT, WAVEFORMATEX**) = 0;
virtual HRESULT STDMETHODCALLTYPE ResetDeviceFormat(PCWSTR) = 0;
virtual HRESULT STDMETHODCALLTYPE SetDeviceFormat(PCWSTR, WAVEFORMATEX*, WAVEFORMATEX*) = 0;
virtual HRESULT STDMETHODCALLTYPE GetProcessingPeriod(PCWSTR, INT, PINT64, PINT64) = 0;
virtual HRESULT STDMETHODCALLTYPE SetProcessingPeriod(PCWSTR, PINT64) = 0;
virtual HRESULT STDMETHODCALLTYPE GetShareMode(PCWSTR, void*) = 0;
virtual HRESULT STDMETHODCALLTYPE SetShareMode(PCWSTR, void*) = 0;
virtual HRESULT STDMETHODCALLTYPE GetPropertyValue(PCWSTR, const PROPERTYKEY&, PROPVARIANT*) = 0;
virtual HRESULT STDMETHODCALLTYPE SetPropertyValue(PCWSTR, const PROPERTYKEY&, PROPVARIANT*) = 0;
virtual HRESULT STDMETHODCALLTYPE SetDefaultEndpoint(PCWSTR wszDeviceId, ERole eRole) = 0;
virtual HRESULT STDMETHODCALLTYPE SetEndpointVisibility(PCWSTR, INT) = 0;
};
// ---------------------------------------------------------------------------
// Constantes / IDs de menu
// ---------------------------------------------------------------------------
#define WM_TRAY (WM_APP + 1)
#define HOTKEY_ID 1
#define ID_DEVICE_BASE 1000
#define ID_HOTKEY_BASE 2000
#define ID_TOGGLE_NOTIFY 3001
#define ID_TOGGLE_AUTOSTART 3002
#define ID_OPEN_CONFIG 3003
#define ID_ABOUT 3004
#define ID_EXIT 3005
struct DeviceInfo { std::wstring id; std::wstring name; };
struct Preset { const wchar_t* label; UINT mods; UINT vk; };
static const Preset PRESETS[] = {
{ L"Ctrl+F1", MOD_CONTROL, VK_F1 },
{ L"Ctrl+F2", MOD_CONTROL, VK_F2 },
{ L"Ctrl+F3", MOD_CONTROL, VK_F3 },
{ L"Ctrl+F4", MOD_CONTROL, VK_F4 },
{ L"Ctrl+Alt+F1", MOD_CONTROL | MOD_ALT, VK_F1 },
{ L"Ctrl+Alt+F2", MOD_CONTROL | MOD_ALT, VK_F2 },
{ L"Ctrl+Shift+F1", MOD_CONTROL | MOD_SHIFT, VK_F1 },
{ L"Alt+F1", MOD_ALT, VK_F1 },
};
static const int PRESET_COUNT = (int)(sizeof(PRESETS) / sizeof(PRESETS[0]));
// ---------------------------------------------------------------------------
// Estado global
// ---------------------------------------------------------------------------
static HWND g_hwnd = nullptr;
static NOTIFYICONDATAW g_nid = {};
static std::wstring g_cfg; // caminho do .ini
static UINT g_hotkeyMods = MOD_CONTROL;
static UINT g_hotkeyVk = VK_F1;
static bool g_notifications = true;
static UINT g_wmTaskbarCreated = 0;
static std::vector<DeviceInfo> g_menuDevices; // snapshot do ultimo menu aberto
// ---------------------------------------------------------------------------
// Utilidades
// ---------------------------------------------------------------------------
static std::vector<std::wstring> Split(const std::wstring& s, wchar_t d)
{
std::vector<std::wstring> out;
std::wstring cur;
for (wchar_t c : s) {
if (c == d) { if (!cur.empty()) out.push_back(cur); cur.clear(); }
else cur += c;
}
if (!cur.empty()) out.push_back(cur);
return out;
}
static std::wstring ExePath()
{
wchar_t buf[MAX_PATH];
GetModuleFileNameW(nullptr, buf, MAX_PATH);
return buf;
}
static std::wstring ConfigPath()
{
wchar_t path[MAX_PATH] = {};
SHGetFolderPathW(nullptr, CSIDL_APPDATA, nullptr, SHGFP_TYPE_CURRENT, path);
std::wstring dir = path;
dir += L"\\AudioSwitcher";
CreateDirectoryW(dir.c_str(), nullptr);
return dir + L"\\AudioSwitcher.ini";
}
// "Ctrl+F1", "Ctrl + Alt + F2", "WIN+K" -> (mods, vk). Retorna false se invalido.
static bool ParseHotkey(const std::wstring& in, UINT& mods, UINT& vk)
{
std::wstring s;
for (wchar_t c : in) if (c != L' ') s += (wchar_t)towupper(c);
mods = 0; vk = 0;
for (auto& p : Split(s, L'+')) {
if (p == L"CTRL" || p == L"CONTROL") mods |= MOD_CONTROL;
else if (p == L"ALT") mods |= MOD_ALT;
else if (p == L"SHIFT") mods |= MOD_SHIFT;
else if (p == L"WIN") mods |= MOD_WIN;
else if (p.size() >= 2 && p[0] == L'F') {
int n = _wtoi(p.c_str() + 1);
if (n >= 1 && n <= 24) vk = VK_F1 + (n - 1);
}
else if (p.size() == 1) {
wchar_t c = p[0];
if ((c >= L'A' && c <= L'Z') || (c >= L'0' && c <= L'9')) vk = c;
}
}
return vk != 0;
}
static std::wstring HotkeyLabel(UINT mods, UINT vk)
{
for (int i = 0; i < PRESET_COUNT; i++)
if (PRESETS[i].mods == mods && PRESETS[i].vk == vk)
return PRESETS[i].label;
std::wstring s;
if (mods & MOD_CONTROL) s += L"Ctrl+";
if (mods & MOD_ALT) s += L"Alt+";
if (mods & MOD_SHIFT) s += L"Shift+";
if (mods & MOD_WIN) s += L"Win+";
if (vk >= VK_F1 && vk <= VK_F24) s += L"F" + std::to_wstring(vk - VK_F1 + 1);
else s += (wchar_t)vk;
return s;
}
// ---------------------------------------------------------------------------
// Enumeracao e troca de dispositivos de audio (Core Audio + IPolicyConfig)
// ---------------------------------------------------------------------------
static std::vector<DeviceInfo> EnumRenderDevices()
{
std::vector<DeviceInfo> out;
IMMDeviceEnumerator* pEnum = nullptr;
if (FAILED(CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr, CLSCTX_ALL,
__uuidof(IMMDeviceEnumerator), (void**)&pEnum)))
return out;
IMMDeviceCollection* pCol = nullptr;
if (SUCCEEDED(pEnum->EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE, &pCol))) {
UINT count = 0;
pCol->GetCount(&count);
for (UINT i = 0; i < count; i++) {
IMMDevice* pDev = nullptr;
if (FAILED(pCol->Item(i, &pDev))) continue;
LPWSTR id = nullptr;
pDev->GetId(&id);
std::wstring name;
IPropertyStore* pProps = nullptr;
if (SUCCEEDED(pDev->OpenPropertyStore(STGM_READ, &pProps))) {
PROPVARIANT v;
PropVariantInit(&v);
if (SUCCEEDED(pProps->GetValue(PKEY_Device_FriendlyName, &v)) && v.vt == VT_LPWSTR)
name = v.pwszVal;
PropVariantClear(&v);
pProps->Release();
}
if (id) {
out.push_back({ id, name.empty() ? L"(dispositivo sem nome)" : name });
CoTaskMemFree(id);
}
pDev->Release();
}
pCol->Release();
}
pEnum->Release();
return out;
}
static std::wstring GetDefaultRenderId()
{
std::wstring result;
IMMDeviceEnumerator* pEnum = nullptr;
if (FAILED(CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr, CLSCTX_ALL,
__uuidof(IMMDeviceEnumerator), (void**)&pEnum)))
return result;
IMMDevice* pDev = nullptr;
if (SUCCEEDED(pEnum->GetDefaultAudioEndpoint(eRender, eConsole, &pDev))) {
LPWSTR id = nullptr;
if (SUCCEEDED(pDev->GetId(&id))) { result = id; CoTaskMemFree(id); }
pDev->Release();
}
pEnum->Release();
return result;
}
static bool SetDefaultRender(const std::wstring& id)
{
IPolicyConfig* pPolicy = nullptr;
if (FAILED(CoCreateInstance(__uuidof(CPolicyConfigClient), nullptr, CLSCTX_ALL,
__uuidof(IPolicyConfig), (void**)&pPolicy)))
return false;
bool ok = true;
ok &= SUCCEEDED(pPolicy->SetDefaultEndpoint(id.c_str(), eConsole));
ok &= SUCCEEDED(pPolicy->SetDefaultEndpoint(id.c_str(), eMultimedia));
ok &= SUCCEEDED(pPolicy->SetDefaultEndpoint(id.c_str(), eCommunications));
pPolicy->Release();
return ok;
}
// ---------------------------------------------------------------------------
// Configuracao (.ini via API do Windows)
// ---------------------------------------------------------------------------
static std::vector<std::wstring> LoadCycleOrder()
{
std::vector<wchar_t> buf(32768);
GetPrivateProfileStringW(L"cycle", L"order", L"", buf.data(), (DWORD)buf.size(), g_cfg.c_str());
return Split(buf.data(), L';');
}
static void SaveCycleOrder(const std::vector<std::wstring>& v)
{
std::wstring s;
for (size_t i = 0; i < v.size(); i++) { if (i) s += L';'; s += v[i]; }
WritePrivateProfileStringW(L"cycle", L"order", s.c_str(), g_cfg.c_str());
}
static void LoadSettings()
{
wchar_t buf[256];
GetPrivateProfileStringW(L"general", L"hotkey", L"Ctrl+F1", buf, 256, g_cfg.c_str());
UINT m, k;
if (ParseHotkey(buf, m, k)) { g_hotkeyMods = m; g_hotkeyVk = k; }
g_notifications = GetPrivateProfileIntW(L"general", L"notifications", 1, g_cfg.c_str()) != 0;
// Primeira execucao: se nao ha ciclo definido, entra com todos os dispositivos ativos.
if (LoadCycleOrder().empty()) {
std::vector<std::wstring> ids;
for (auto& d : EnumRenderDevices()) ids.push_back(d.id);
SaveCycleOrder(ids);
}
// Garante que as chaves existam no arquivo (para o usuario poder editar).
WritePrivateProfileStringW(L"general", L"hotkey",
HotkeyLabel(g_hotkeyMods, g_hotkeyVk).c_str(), g_cfg.c_str());
WritePrivateProfileStringW(L"general", L"notifications",
g_notifications ? L"1" : L"0", g_cfg.c_str());
}
// ---------------------------------------------------------------------------
// Iniciar com o Windows (HKCU\...\Run)
// ---------------------------------------------------------------------------
static const wchar_t* RUN_KEY = L"Software\\Microsoft\\Windows\\CurrentVersion\\Run";
static const wchar_t* RUN_NAME = L"AudioSwitcher";
static bool IsAutostart()
{
HKEY hk;
if (RegOpenKeyExW(HKEY_CURRENT_USER, RUN_KEY, 0, KEY_READ, &hk) != ERROR_SUCCESS)
return false;
wchar_t buf[MAX_PATH * 2] = {};
DWORD sz = sizeof(buf), type = 0;
bool present = RegQueryValueExW(hk, RUN_NAME, nullptr, &type, (LPBYTE)buf, &sz) == ERROR_SUCCESS;
RegCloseKey(hk);
return present;
}
static void SetAutostart(bool on)
{
HKEY hk;
if (RegOpenKeyExW(HKEY_CURRENT_USER, RUN_KEY, 0, KEY_SET_VALUE, &hk) != ERROR_SUCCESS)
return;
if (on) {
std::wstring cmd = L"\"" + ExePath() + L"\"";
RegSetValueExW(hk, RUN_NAME, 0, REG_SZ, (const BYTE*)cmd.c_str(),
(DWORD)((cmd.size() + 1) * sizeof(wchar_t)));
} else {
RegDeleteValueW(hk, RUN_NAME);
}
RegCloseKey(hk);
}
// ---------------------------------------------------------------------------
// Bandeja: notificacoes e tooltip
// ---------------------------------------------------------------------------
static void UpdateTip(const std::wstring& deviceName)
{
std::wstring tip = L"AudioSwitcher\n" + deviceName + L"\n" +
HotkeyLabel(g_hotkeyMods, g_hotkeyVk) + L" para alternar";
lstrcpynW(g_nid.szTip, tip.c_str(), 128);
g_nid.uFlags = NIF_TIP;
Shell_NotifyIconW(NIM_MODIFY, &g_nid);
g_nid.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;
}
static void Notify(const std::wstring& title, const std::wstring& text)
{
g_nid.uFlags = NIF_INFO;
lstrcpynW(g_nid.szInfoTitle, title.c_str(), 64);
lstrcpynW(g_nid.szInfo, text.c_str(), 256);
g_nid.dwInfoFlags = NIIF_NONE;
Shell_NotifyIconW(NIM_MODIFY, &g_nid);
g_nid.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;
}
// ---------------------------------------------------------------------------
// Acao principal: ciclar para o proximo dispositivo
// ---------------------------------------------------------------------------
static void DoCycle()
{
std::vector<DeviceInfo> devices = EnumRenderDevices();
if (devices.empty()) { Notify(L"AudioSwitcher", L"Nenhum dispositivo de audio ativo."); return; }
// Ordem do ciclo, filtrada pelos que estao ativos agora.
std::vector<std::wstring> order;
for (auto& id : LoadCycleOrder())
for (auto& d : devices)
if (d.id == id) { order.push_back(id); break; }
if (order.size() < 2) {
// Ciclo vazio ou com so 1 valido -> usa todos os ativos.
order.clear();
for (auto& d : devices) order.push_back(d.id);
}
if (order.empty()) return;
std::wstring cur = GetDefaultRenderId();
size_t idx = 0; bool found = false;
for (size_t i = 0; i < order.size(); i++)
if (order[i] == cur) { idx = i; found = true; break; }
std::wstring target = found ? order[(idx + 1) % order.size()] : order[0];
if (target == cur) return; // nada a fazer (so 1 dispositivo)
std::wstring name;
for (auto& d : devices) if (d.id == target) name = d.name;
if (SetDefaultRender(target)) {
UpdateTip(name);
if (g_notifications) Notify(L"Saida de audio", name);
} else {
Notify(L"AudioSwitcher", L"Falha ao alternar o dispositivo.");
}
}
// ---------------------------------------------------------------------------
// Menu da bandeja
// ---------------------------------------------------------------------------
static void ApplyHotkey()
{
UnregisterHotKey(g_hwnd, HOTKEY_ID);
if (!RegisterHotKey(g_hwnd, HOTKEY_ID, g_hotkeyMods | MOD_NOREPEAT, g_hotkeyVk)) {
MessageBoxW(g_hwnd,
L"Nao foi possivel registrar esse atalho.\n"
L"Provavelmente ja esta em uso por outro programa.\n"
L"Escolha outro no menu da bandeja.",
L"AudioSwitcher", MB_ICONWARNING);
}
UpdateTip(L"");
}
static void ToggleDevice(const std::wstring& id)
{
std::vector<std::wstring> v = LoadCycleOrder();
auto it = std::find(v.begin(), v.end(), id);
if (it != v.end()) v.erase(it);
else v.push_back(id);
SaveCycleOrder(v);
}
static void ShowTrayMenu()
{
std::vector<DeviceInfo> devices = EnumRenderDevices();
std::vector<std::wstring> cycle = LoadCycleOrder();
std::wstring curId = GetDefaultRenderId();
std::wstring curName = L"(nenhuma)";
for (auto& d : devices) if (d.id == curId) curName = d.name;
g_menuDevices = devices;
HMENU m = CreatePopupMenu();
AppendMenuW(m, MF_STRING | MF_GRAYED, 0, (L"Saida atual: " + curName).c_str());
AppendMenuW(m, MF_SEPARATOR, 0, nullptr);
AppendMenuW(m, MF_STRING | MF_GRAYED, 0, L"Dispositivos no ciclo (clique p/ marcar):");
for (size_t i = 0; i < devices.size(); i++) {
bool inCycle = std::find(cycle.begin(), cycle.end(), devices[i].id) != cycle.end();
UINT flags = MF_STRING | (inCycle ? MF_CHECKED : MF_UNCHECKED);
AppendMenuW(m, flags, ID_DEVICE_BASE + (UINT)i, devices[i].name.c_str());
}
AppendMenuW(m, MF_SEPARATOR, 0, nullptr);
HMENU hk = CreatePopupMenu();
for (int i = 0; i < PRESET_COUNT; i++) {
bool sel = (g_hotkeyMods == PRESETS[i].mods && g_hotkeyVk == PRESETS[i].vk);
AppendMenuW(hk, MF_STRING | (sel ? MF_CHECKED : 0), ID_HOTKEY_BASE + i, PRESETS[i].label);
}
AppendMenuW(m, MF_POPUP, (UINT_PTR)hk,
(L"Atalho: " + HotkeyLabel(g_hotkeyMods, g_hotkeyVk)).c_str());
AppendMenuW(m, MF_STRING | (g_notifications ? MF_CHECKED : 0), ID_TOGGLE_NOTIFY,
L"Notificar ao trocar");
AppendMenuW(m, MF_STRING | (IsAutostart() ? MF_CHECKED : 0), ID_TOGGLE_AUTOSTART,
L"Iniciar com o Windows");
AppendMenuW(m, MF_STRING, ID_OPEN_CONFIG, L"Abrir arquivo de configuracao");
AppendMenuW(m, MF_SEPARATOR, 0, nullptr);
AppendMenuW(m, MF_STRING, ID_ABOUT, L"Sobre");
AppendMenuW(m, MF_STRING, ID_EXIT, L"Sair");
POINT pt;
GetCursorPos(&pt);
SetForegroundWindow(g_hwnd);
TrackPopupMenu(m, TPM_RIGHTBUTTON | TPM_BOTTOMALIGN, pt.x, pt.y, 0, g_hwnd, nullptr);
PostMessageW(g_hwnd, WM_NULL, 0, 0); // corrige bug classico do TrackPopupMenu
DestroyMenu(m);
}
// ---------------------------------------------------------------------------
// Janela oculta / loop de mensagens
// ---------------------------------------------------------------------------
static void HandleCommand(int id)
{
if (id >= ID_DEVICE_BASE && id < ID_DEVICE_BASE + (int)g_menuDevices.size()) {
ToggleDevice(g_menuDevices[id - ID_DEVICE_BASE].id);
return;
}
if (id >= ID_HOTKEY_BASE && id < ID_HOTKEY_BASE + PRESET_COUNT) {
const Preset& p = PRESETS[id - ID_HOTKEY_BASE];
g_hotkeyMods = p.mods;
g_hotkeyVk = p.vk;
WritePrivateProfileStringW(L"general", L"hotkey", p.label, g_cfg.c_str());
ApplyHotkey();
return;
}
switch (id) {
case ID_TOGGLE_NOTIFY:
g_notifications = !g_notifications;
WritePrivateProfileStringW(L"general", L"notifications",
g_notifications ? L"1" : L"0", g_cfg.c_str());
break;
case ID_TOGGLE_AUTOSTART:
SetAutostart(!IsAutostart());
break;
case ID_OPEN_CONFIG:
ShellExecuteW(nullptr, L"open", L"notepad.exe", g_cfg.c_str(), nullptr, SW_SHOW);
break;
case ID_ABOUT: {
std::wstring msg =
L"AudioSwitcher\n\n"
L"Alterna a saida de audio padrao do Windows por hotkey global.\n"
L"Marque no menu quais dispositivos entram no ciclo e aperte o atalho\n"
L"para pular para o proximo.\n\n"
L"App nativo, sem dependencias. Configuracao em:\n" + g_cfg;
MessageBoxW(g_hwnd, msg.c_str(), L"Sobre o AudioSwitcher", MB_ICONINFORMATION);
break;
}
case ID_EXIT:
DestroyWindow(g_hwnd);
break;
}
}
static LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
if (msg == g_wmTaskbarCreated) {
Shell_NotifyIconW(NIM_ADD, &g_nid);
Shell_NotifyIconW(NIM_SETVERSION, &g_nid);
return 0;
}
switch (msg) {
case WM_HOTKEY:
if (wParam == HOTKEY_ID) DoCycle();
return 0;
case WM_TRAY:
switch (LOWORD(lParam)) {
case WM_LBUTTONUP:
case WM_CONTEXTMENU:
case WM_RBUTTONUP:
ShowTrayMenu();
break;
case WM_LBUTTONDBLCLK:
DoCycle();
break;
}
return 0;
case WM_COMMAND:
HandleCommand(LOWORD(wParam));
return 0;
case WM_DESTROY:
Shell_NotifyIconW(NIM_DELETE, &g_nid);
UnregisterHotKey(hwnd, HOTKEY_ID);
PostQuitMessage(0);
return 0;
}
return DefWindowProcW(hwnd, msg, wParam, lParam);
}
// Escreve texto UTF-8 no stdout herdado (pipe/console) do processo pai.
static void CliPrint(const std::wstring& ws)
{
HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
if (!h || h == INVALID_HANDLE_VALUE) {
AttachConsole(ATTACH_PARENT_PROCESS);
h = GetStdHandle(STD_OUTPUT_HANDLE);
}
if (!h || h == INVALID_HANDLE_VALUE) return;
int n = WideCharToMultiByte(CP_UTF8, 0, ws.c_str(), -1, nullptr, 0, nullptr, nullptr);
if (n <= 1) return;
std::vector<char> buf(n);
WideCharToMultiByte(CP_UTF8, 0, ws.c_str(), -1, buf.data(), n, nullptr, nullptr);
DWORD written = 0, mode = 0;
if (GetConsoleMode(h, &mode)) {
WriteConsoleW(h, ws.c_str(), (DWORD)ws.size(), &written, nullptr);
} else {
WriteFile(h, buf.data(), (DWORD)(n - 1), &written, nullptr);
}
}
static int RunCli(const std::wstring& arg)
{
CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
g_cfg = ConfigPath();
int rc = 0;
if (arg == L"--list") {
std::wstring cur = GetDefaultRenderId();
std::vector<std::wstring> cycle = LoadCycleOrder();
std::wstring out = L"\n Dispositivos de saida ativos:\n\n";
for (auto& d : EnumRenderDevices()) {
bool isCur = (d.id == cur);
bool inCyc = std::find(cycle.begin(), cycle.end(), d.id) != cycle.end();
out += L" ";
out += isCur ? L"* " : L" ";
out += inCyc ? L"[ciclo] " : L" ";
out += d.name;
out += L"\n";
}
out += L"\n (* = saida padrao atual)\n\n";
CliPrint(out);
}
else if (arg == L"--cycle") {
LoadSettings();
DoCycle();
std::wstring cur = GetDefaultRenderId();
for (auto& d : EnumRenderDevices())
if (d.id == cur) CliPrint(L"Saida de audio: " + d.name + L"\n");
}
else {
CliPrint(L"AudioSwitcher\n"
L" (sem argumentos) inicia o app na bandeja do sistema\n"
L" --list lista os dispositivos de saida\n"
L" --cycle alterna para o proximo dispositivo do ciclo\n");
rc = 2;
}
CoUninitialize();
return rc;
}
int WINAPI wWinMain(HINSTANCE hInst, HINSTANCE, PWSTR lpCmdLine, int)
{
if (lpCmdLine && lpCmdLine[0]) {
std::wstring arg(lpCmdLine);
size_t a = arg.find_first_not_of(L" \t");
size_t b = arg.find_last_not_of(L" \t\r\n");
arg = (a == std::wstring::npos) ? L"" : arg.substr(a, b - a + 1);
return RunCli(arg);
}
// Instancia unica.
HANDLE mtx = CreateMutexW(nullptr, FALSE, L"Local\\AudioSwitcher_SingleInstance");
if (mtx && GetLastError() == ERROR_ALREADY_EXISTS) {
// Ja em execucao: sinaliza a instancia ativa para ela ciclar, e sai.
// Ja em execucao: sinaliza a instancia ativa para ciclar, e sai.
HWND existing = FindWindowExW(HWND_MESSAGE, nullptr, L"AudioSwitcherWnd", nullptr);
if (existing) PostMessageW(existing, WM_HOTKEY, HOTKEY_ID, 0);
return 0;
}
CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
g_cfg = ConfigPath();
LoadSettings();
WNDCLASSEXW wc = { sizeof(wc) };
wc.lpfnWndProc = WndProc;
wc.hInstance = hInst;
wc.lpszClassName = L"AudioSwitcherWnd";
wc.hIcon = (HICON)LoadImageW(hInst, MAKEINTRESOURCEW(1), IMAGE_ICON, 0, 0,
LR_DEFAULTSIZE | LR_DEFAULTCOLOR);
RegisterClassExW(&wc);
g_hwnd = CreateWindowExW(0, wc.lpszClassName, L"AudioSwitcher", 0,
0, 0, 0, 0, HWND_MESSAGE, nullptr, hInst, nullptr);
g_wmTaskbarCreated = RegisterWindowMessageW(L"TaskbarCreated");
g_nid.cbSize = sizeof(g_nid);
g_nid.hWnd = g_hwnd;
g_nid.uID = 1;
g_nid.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;
g_nid.uCallbackMessage = WM_TRAY;
g_nid.hIcon = (HICON)LoadImageW(hInst, MAKEINTRESOURCEW(1), IMAGE_ICON,
GetSystemMetrics(SM_CXSMICON),
GetSystemMetrics(SM_CYSMICON), LR_DEFAULTCOLOR);
if (!g_nid.hIcon) g_nid.hIcon = LoadIconW(nullptr, IDI_APPLICATION);
g_nid.uVersion = NOTIFYICON_VERSION_4;
lstrcpynW(g_nid.szTip, L"AudioSwitcher", 128);
Shell_NotifyIconW(NIM_ADD, &g_nid);
Shell_NotifyIconW(NIM_SETVERSION, &g_nid);
ApplyHotkey();
{
std::wstring cur = GetDefaultRenderId(), name = L"(desconhecida)";
for (auto& d : EnumRenderDevices()) if (d.id == cur) name = d.name;
UpdateTip(name);
}
MSG m;
while (GetMessageW(&m, nullptr, 0, 0) > 0) {
TranslateMessage(&m);
DispatchMessageW(&m);
}
CoUninitialize();
if (mtx) CloseHandle(mtx);
return 0;
}