-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
1343 lines (1171 loc) · 51.3 KB
/
Copy pathmain.cpp
File metadata and controls
1343 lines (1171 loc) · 51.3 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
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#define NOMINMAX
#include "Common.h"
#include <shlobj.h>
#include <sstream>
#include <vector>
using namespace Gdiplus;
// Global Instances & Handles
HINSTANCE g_hInstance = NULL;
HWND g_hwndMain = NULL;
HWND g_hwndFlyout = NULL;
NOTIFYICONDATAW g_nid = {};
HICON g_hCurrentTrayIcon = NULL;
UINT g_uTaskbarCreated = 0; // "TaskbarCreated" broadcast (sent when Explorer restarts)
UINT g_uRestoreTray = 0; // private message: a 2nd instance asks us to re-show the icon
bool g_trayIconAdded = false;
AppConfig g_config;
ULONG_PTR g_gdiplusToken = 0;
bool g_isDraggingSlider = false;
bool g_isFlyoutVisible = false;
std::vector<MonitorEntry> g_monitors;
std::vector<MonitorHandleItem*> g_items; // flat list of every physical monitor, in display order
std::wstring g_primaryMonitorName = L"";
// Paths
std::wstring g_exePath;
std::wstring g_iniPath;
// Forward Declarations
LRESULT CALLBACK MainWndProc(HWND, UINT, WPARAM, LPARAM);
LRESULT CALLBACK FlyoutWndProc(HWND, UINT, WPARAM, LPARAM);
void LoadConfig();
void SaveConfig();
void SetAutoStart(bool enable);
bool IsAutoStartEnabled();
void InitPhysicalMonitors();
void ReleasePhysicalMonitors();
void ApplyHardwareSettings();
void ApplyItemSettings(MonitorHandleItem& item);
void RebuildItemIndex();
MonitorHandleItem* ActiveItem();
int GetTargetBrightness();
void SetTargetMode(bool syncAll, int index);
void SaveMonitorLevels();
void LayoutFlyout();
void ResetBaseContrast();
void UpdateTrayIcon();
bool AddTrayIcon();
std::wstring BuildTrayTip();
void ShowFlyout(bool show);
void SetBrightness(int val);
void ChangeBrightnessBy(int delta);
void PositionFlyoutNearTray();
void SetLanguage(Language lang);
// Helper strings based on language (English default)
const wchar_t* GetStrAllMonitors() { return g_config.lang == Language::TH ? L"ทุกจอ" : L"All"; }
const wchar_t* GetStrMonitorShort() { return g_config.lang == Language::TH ? L"จอ" : L"Mon"; }
// Title reflects what the slider is currently driving: every monitor, or one of them.
const wchar_t* GetStrTitle() {
static std::wstring title;
bool isTH = (g_config.lang == Language::TH);
if (g_items.size() > 1 && g_config.syncAll) {
title = (isTH ? L"ทุกจอภาพ (" : L"All Monitors (")
+ std::to_wstring(g_items.size()) + (isTH ? L" จอ)" : L")");
return title.c_str();
}
MonitorHandleItem* item = ActiveItem();
if (item && item->szDescription[0] != L'\0') {
if (g_items.size() > 1) {
title = (isTH ? L"จอ " : L"Monitor ") + std::to_wstring(g_config.selectedMonitor + 1)
+ L" - " + item->szDescription;
} else {
title = item->szDescription;
}
return title.c_str();
}
title = isTH ? L"ความสว่างหน้าจอ (DDC/CI)" : L"Screen Brightness (DDC/CI)";
return title.c_str();
}
const wchar_t* GetStrHotkeys() { return g_config.lang == Language::TH ? L"คีย์ลัด Ctrl+Alt+↑/↓" : L"Hotkeys: Ctrl+Alt+↑/↓"; }
const wchar_t* GetStrAutoStart() { return g_config.lang == Language::TH ? L"เปิดพร้อม Windows" : L"Start with Windows"; }
const wchar_t* GetStrResetContrast() { return g_config.lang == Language::TH ? L"↺ รีเซ็ต Contrast" : L"↺ Reset Contrast"; }
// Registry key for AutoStart
const wchar_t* REG_RUN_KEY = L"Software\\Microsoft\\Windows\\CurrentVersion\\Run";
const wchar_t* APP_NAME = L"ScreenBrightnessDDC";
std::wstring GetExecutablePath() {
wchar_t buffer[MAX_PATH];
GetModuleFileNameW(NULL, buffer, MAX_PATH);
return std::wstring(buffer);
}
std::wstring GetIniFilePath() {
wchar_t buffer[MAX_PATH];
GetModuleFileNameW(NULL, buffer, MAX_PATH);
wchar_t* lastSlash = wcsrchr(buffer, L'\\');
if (lastSlash) {
*(lastSlash + 1) = L'\0';
}
return std::wstring(buffer) + L"config.ini";
}
void LoadConfig() {
g_iniPath = GetIniFilePath();
g_config.brightness = GetPrivateProfileIntW(L"Settings", L"Brightness", 50, g_iniPath.c_str());
g_config.baseContrast = GetPrivateProfileIntW(L"Settings", L"BaseContrast", -1, g_iniPath.c_str());
wchar_t langBuf[16] = {};
GetPrivateProfileStringW(L"Settings", L"Language", L"EN", langBuf, 16, g_iniPath.c_str());
if (_wcsicmp(langBuf, L"TH") == 0) {
g_config.lang = Language::TH;
} else {
g_config.lang = Language::EN;
}
g_config.syncAll = (GetPrivateProfileIntW(L"Settings", L"SyncAllMonitors", 1, g_iniPath.c_str()) != 0);
g_config.selectedMonitor = GetPrivateProfileIntW(L"Settings", L"SelectedMonitor", 0, g_iniPath.c_str());
if (g_config.selectedMonitor < 0) g_config.selectedMonitor = 0;
g_config.autoStart = IsAutoStartEnabled();
if (g_config.brightness < 0) g_config.brightness = 0;
if (g_config.brightness > 100) g_config.brightness = 100;
}
void SaveConfig() {
WritePrivateProfileStringW(L"Settings", L"Brightness", std::to_wstring(g_config.brightness).c_str(), g_iniPath.c_str());
WritePrivateProfileStringW(L"Settings", L"BaseContrast", std::to_wstring(g_config.baseContrast).c_str(), g_iniPath.c_str());
WritePrivateProfileStringW(L"Settings", L"Language", g_config.lang == Language::TH ? L"TH" : L"EN", g_iniPath.c_str());
WritePrivateProfileStringW(L"Settings", L"SyncAllMonitors", g_config.syncAll ? L"1" : L"0", g_iniPath.c_str());
WritePrivateProfileStringW(L"Settings", L"SelectedMonitor", std::to_wstring(g_config.selectedMonitor).c_str(), g_iniPath.c_str());
}
// Per-monitor levels live in their own [Monitors] section, keyed by display device.
void SaveMonitorLevels() {
if (g_iniPath.empty()) return;
for (auto* item : g_items) {
if (item->key.empty()) continue;
WritePrivateProfileStringW(L"Monitors", item->key.c_str(),
std::to_wstring(item->brightness).c_str(), g_iniPath.c_str());
}
}
bool IsAutoStartEnabled() {
HKEY hKey;
if (RegOpenKeyExW(HKEY_CURRENT_USER, REG_RUN_KEY, 0, KEY_READ, &hKey) == ERROR_SUCCESS) {
wchar_t path[MAX_PATH];
DWORD pathLen = sizeof(path);
DWORD type = 0;
LONG res = RegQueryValueExW(hKey, APP_NAME, NULL, &type, (LPBYTE)path, &pathLen);
RegCloseKey(hKey);
return (res == ERROR_SUCCESS);
}
return false;
}
void SetAutoStart(bool enable) {
HKEY hKey;
if (RegOpenKeyExW(HKEY_CURRENT_USER, REG_RUN_KEY, 0, KEY_SET_VALUE, &hKey) == ERROR_SUCCESS) {
if (enable) {
std::wstring cmd = L"\"" + g_exePath + L"\"";
RegSetValueExW(hKey, APP_NAME, 0, REG_SZ, (const BYTE*)cmd.c_str(), (DWORD)((cmd.length() + 1) * sizeof(wchar_t)));
} else {
RegDeleteValueW(hKey, APP_NAME);
}
RegCloseKey(hKey);
}
g_config.autoStart = enable;
}
void SetLanguage(Language lang) {
if (g_config.lang != lang) {
g_config.lang = lang;
SaveConfig();
UpdateTrayIcon();
if (g_hwndFlyout && IsWindowVisible(g_hwndFlyout)) {
InvalidateRect(g_hwndFlyout, NULL, FALSE);
}
}
}
// -------------------------------------------------------------
// Hardware DDC/CI Backlight & Proportional Contrast Management
// -------------------------------------------------------------
BOOL CALLBACK EnumMonitorsProc(HMONITOR hMonitor, HDC, LPRECT, LPARAM) {
// Stable key for the ini file: "\\.\DISPLAY1" -> "DISPLAY1"
std::wstring devKey = L"DISPLAY";
MONITORINFOEXW mi = {};
mi.cbSize = sizeof(mi);
if (GetMonitorInfoW(hMonitor, (LPMONITORINFO)&mi)) {
devKey = mi.szDevice;
size_t slash = devKey.find_last_of(L'\\');
if (slash != std::wstring::npos) devKey = devKey.substr(slash + 1);
}
DWORD count = 0;
if (GetNumberOfPhysicalMonitorsFromHMONITOR(hMonitor, &count) && count > 0) {
LPPHYSICAL_MONITOR pPhys = (LPPHYSICAL_MONITOR)malloc(count * sizeof(PHYSICAL_MONITOR));
if (pPhys && GetPhysicalMonitorsFromHMONITOR(hMonitor, count, pPhys)) {
MonitorEntry entry = {};
entry.hMonitor = hMonitor;
entry.count = count;
entry.pPhysicalMonitors = pPhys;
for (DWORD i = 0; i < count; ++i) {
MonitorHandleItem item = {};
item.hPhysicalMonitor = pPhys[i].hPhysicalMonitor;
wcsncpy_s(item.szDescription, pPhys[i].szPhysicalMonitorDescription, _TRUNCATE);
// Remembered level for this exact display (falls back to the shared one)
item.key = devKey + L"_" + std::to_wstring(i);
item.brightness = GetPrivateProfileIntW(L"Monitors", item.key.c_str(),
g_config.brightness, g_iniPath.c_str());
if (item.brightness < 0) item.brightness = 0;
if (item.brightness > 100) item.brightness = 100;
if (g_config.syncAll) item.brightness = g_config.brightness;
// 1. Read Brightness limits
DWORD minB = 0, curB = 50, maxB = 100;
if (GetMonitorBrightness(item.hPhysicalMonitor, &minB, &curB, &maxB)) {
item.minBrightness = minB;
item.curBrightness = curB;
item.maxBrightness = maxB;
if (g_primaryMonitorName.empty() && item.szDescription[0] != L'\0') {
g_primaryMonitorName = item.szDescription;
}
} else {
item.minBrightness = 0;
item.curBrightness = 50;
item.maxBrightness = 100;
}
// 2. Read Contrast limits and baseline
DWORD minC = 0, curC = 50, maxC = 100;
if (GetMonitorContrast(item.hPhysicalMonitor, &minC, &curC, &maxC)) {
item.minContrast = minC;
item.curContrast = curC;
item.maxContrast = maxC;
item.supportsContrast = true;
// If baseContrast has not been set yet, use the monitor's original contrast setting!
if (g_config.baseContrast < (int)minC || g_config.baseContrast > (int)maxC) {
g_config.baseContrast = (curC > 0) ? curC : 50;
SaveConfig();
}
item.baseContrast = (DWORD)g_config.baseContrast;
} else {
item.minContrast = 0;
item.curContrast = 50;
item.maxContrast = 100;
item.baseContrast = 50;
item.supportsContrast = false;
}
entry.items.push_back(item);
}
g_monitors.push_back(entry);
} else if (pPhys) {
free(pPhys);
}
}
return TRUE;
}
void ReleasePhysicalMonitors() {
g_items.clear();
for (auto& entry : g_monitors) {
if (entry.pPhysicalMonitors && entry.count > 0) {
DestroyPhysicalMonitors(entry.count, entry.pPhysicalMonitors);
free(entry.pPhysicalMonitors);
}
}
g_monitors.clear();
}
// Flattens every physical monitor into one indexed list the UI can address.
// Safe to take pointers here: g_monitors is fully built before this runs.
void RebuildItemIndex() {
g_items.clear();
for (auto& entry : g_monitors) {
for (auto& item : entry.items) {
g_items.push_back(&item);
}
}
for (size_t i = 0; i < g_items.size(); ++i) {
g_items[i]->label = std::to_wstring(i + 1);
}
if (g_config.selectedMonitor < 0 || g_config.selectedMonitor >= (int)g_items.size()) {
g_config.selectedMonitor = 0;
}
}
MonitorHandleItem* ActiveItem() {
if (g_items.empty()) return NULL;
int idx = g_config.selectedMonitor;
if (idx < 0 || idx >= (int)g_items.size()) idx = 0;
return g_items[idx];
}
// The level the slider, the tray icon and the presets all refer to.
int GetTargetBrightness() {
if (!g_config.syncAll) {
MonitorHandleItem* item = ActiveItem();
if (item) return item->brightness;
}
return g_config.brightness;
}
void InitPhysicalMonitors() {
ReleasePhysicalMonitors();
g_primaryMonitorName.clear();
EnumDisplayMonitors(NULL, NULL, EnumMonitorsProc, 0);
RebuildItemIndex();
LayoutFlyout(); // the monitor picker row appears/disappears with the monitor count
// Apply current settings to monitors
ApplyHardwareSettings();
}
// Reset Contrast to standard default / monitor's native setting
void ResetBaseContrast() {
g_config.baseContrast = 50; // Standard monitor default
for (auto& entry : g_monitors) {
for (auto& item : entry.items) {
DWORD minC = 0, curC = 50, maxC = 100;
if (GetMonitorContrast(item.hPhysicalMonitor, &minC, &curC, &maxC)) {
if (curC > 0 && curC <= maxC) {
g_config.baseContrast = curC;
}
}
item.baseContrast = (DWORD)g_config.baseContrast;
}
}
SaveConfig();
ApplyHardwareSettings();
if (g_hwndFlyout && IsWindowVisible(g_hwndFlyout)) {
InvalidateRect(g_hwndFlyout, NULL, FALSE);
}
}
// Adjusts one monitor: hardware brightness (0-100%) plus contrast scaled from 0 up to its baseContrast.
void ApplyItemSettings(MonitorHandleItem& item) {
int val = item.brightness;
if (val < 0) val = 0;
if (val > 100) val = 100;
// 1. Calculate & Set Hardware Brightness (0% to 100% of max)
DWORD rangeB = item.maxBrightness - item.minBrightness;
DWORD targetB = item.minBrightness + (DWORD)((val * (float)rangeB) / 100.0f + 0.5f);
if (targetB > item.maxBrightness) targetB = item.maxBrightness;
if (targetB < item.minBrightness) targetB = item.minBrightness;
SetMonitorBrightness(item.hPhysicalMonitor, targetB);
item.curBrightness = targetB;
// 2. Calculate & Set Hardware Contrast:
// At 100% slider -> Contrast = original baseContrast (e.g. 50)
// At 0% slider -> Contrast = 0 (minContrast)
if (item.supportsContrast) {
DWORD targetC = item.minContrast + (DWORD)(((float)val / 100.0f) * (item.baseContrast - item.minContrast) + 0.5f);
if (targetC > item.baseContrast) targetC = item.baseContrast;
if (targetC < item.minContrast) targetC = item.minContrast;
SetMonitorContrast(item.hPhysicalMonitor, targetC);
item.curContrast = targetC;
}
}
// Pushes every monitor's own level to the hardware.
void ApplyHardwareSettings() {
for (auto* item : g_items) {
ApplyItemSettings(*item);
}
}
// -------------------------------------------------------------
// Dynamic System Tray Icon with Brightness Percentage
// -------------------------------------------------------------
HICON CreateBrightnessTrayIcon(int brightness) {
int iconSize = 32;
Bitmap bmp(iconSize, iconSize, PixelFormat32bppARGB);
Graphics g(&bmp);
g.SetSmoothingMode(SmoothingModeAntiAlias);
g.SetTextRenderingHint(TextRenderingHintClearTypeGridFit);
// Dark pill background for contrast
SolidBrush bgBrush(Color(235, 20, 20, 22));
g.FillEllipse(&bgBrush, 0, 0, iconSize, iconSize);
Pen borderPen(Color(180, 80, 80, 85), 1.5f);
g.DrawEllipse(&borderPen, 0.75f, 0.75f, iconSize - 1.5f, iconSize - 1.5f);
// Number text color (Warm Amber/Orange like ClickMonitorDDC)
Color textColor;
if (brightness >= 75) {
textColor = Color(255, 255, 190, 0); // Amber Gold
} else if (brightness >= 40) {
textColor = Color(255, 255, 140, 0); // Vibrant Orange
} else {
textColor = Color(255, 255, 95, 45); // Deep Coral Orange
}
SolidBrush textBrush(textColor);
std::wstring textStr = std::to_wstring(brightness);
FontFamily fontFamily(L"Segoe UI");
REAL fontSize = 16.5f;
if (textStr.length() == 3) {
fontSize = 11.5f; // "100"
} else if (textStr.length() == 2) {
fontSize = 16.5f;
} else {
fontSize = 18.0f;
}
Font font(&fontFamily, fontSize, FontStyleBold, UnitPixel);
StringFormat format;
format.SetAlignment(StringAlignmentCenter);
format.SetLineAlignment(StringAlignmentCenter);
RectF layoutRect(0.0f, 0.0f, (REAL)iconSize, (REAL)iconSize);
g.DrawString(textStr.c_str(), -1, &font, layoutRect, &format, &textBrush);
HICON hIcon = NULL;
bmp.GetHICON(&hIcon);
return hIcon;
}
std::wstring BuildTrayTip() {
std::wstring target;
if (g_items.size() > 1) {
target = std::wstring(L" [") + GetStrTitle() + L"]";
}
if (g_config.lang == Language::TH) {
return L"ความสว่างหน้าจอ: " + std::to_wstring(GetTargetBrightness()) + L"%" + target + L"\n(คลิกซ้าย: ปรับแถบเลื่อน / ล้อเมาส์: ปรับเร็ว)";
}
return L"Screen Brightness: " + std::to_wstring(GetTargetBrightness()) + L"%" + target + L"\n(Left-click: Slider / Wheel: Fast Adjust)";
}
// (Re)registers the notification-area icon.
// Called at startup, after every Explorer restart, and whenever NIM_MODIFY fails.
// Without this the icon disappears for good as soon as the taskbar is rebuilt.
bool AddTrayIcon() {
if (!g_hwndMain) return false;
// Drop any stale registration first (no-op when there is none).
Shell_NotifyIconW(NIM_DELETE, &g_nid);
ZeroMemory(&g_nid, sizeof(g_nid));
g_nid.cbSize = sizeof(NOTIFYICONDATAW);
g_nid.hWnd = g_hwndMain;
g_nid.uID = ID_TRAY_ICON;
g_nid.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
g_nid.uCallbackMessage = WM_TRAYICON;
if (!g_hCurrentTrayIcon) {
g_hCurrentTrayIcon = CreateBrightnessTrayIcon(GetTargetBrightness());
}
g_nid.hIcon = g_hCurrentTrayIcon;
wcsncpy_s(g_nid.szTip, BuildTrayTip().c_str(), _TRUNCATE);
g_trayIconAdded = (Shell_NotifyIconW(NIM_ADD, &g_nid) != FALSE);
return g_trayIconAdded;
}
void UpdateTrayIcon() {
HICON hNewIcon = CreateBrightnessTrayIcon(GetTargetBrightness());
HICON hOldIcon = g_hCurrentTrayIcon;
g_hCurrentTrayIcon = hNewIcon;
g_nid.uFlags = NIF_ICON | NIF_TIP | NIF_MESSAGE;
g_nid.hIcon = hNewIcon;
wcsncpy_s(g_nid.szTip, BuildTrayTip().c_str(), _TRUNCATE);
// If the shell forgot us (taskbar rebuilt) NIM_MODIFY fails - re-add instead.
if (!g_trayIconAdded || !Shell_NotifyIconW(NIM_MODIFY, &g_nid)) {
AddTrayIcon();
}
if (hOldIcon) {
DestroyIcon(hOldIcon);
}
}
// -------------------------------------------------------------
// Brightness Value Adjustments
// -------------------------------------------------------------
void SetBrightness(int val) {
if (val < 0) val = 0;
if (val > 100) val = 100;
if (g_config.syncAll || g_items.empty()) {
// Mode 1: every monitor moves together.
if (g_config.brightness == val) return;
g_config.brightness = val;
for (auto* item : g_items) {
item->brightness = val;
ApplyItemSettings(*item);
}
} else {
// Mode 2: only the selected monitor moves.
MonitorHandleItem* item = ActiveItem();
if (!item || item->brightness == val) return;
item->brightness = val;
g_config.brightness = val; // remembered as the default for newly attached displays
ApplyItemSettings(*item);
}
UpdateTrayIcon();
if (g_hwndFlyout && IsWindowVisible(g_hwndFlyout)) {
InvalidateRect(g_hwndFlyout, NULL, FALSE);
}
// Dragging fires this on every mouse move; persist once when the drag ends instead.
if (!g_isDraggingSlider) {
SaveConfig();
SaveMonitorLevels();
}
}
void ChangeBrightnessBy(int delta) {
SetBrightness(GetTargetBrightness() + delta);
}
// Switches between "all monitors together" and "one specific monitor".
void SetTargetMode(bool syncAll, int index) {
if (!syncAll) {
if (index < 0 || index >= (int)g_items.size()) return;
g_config.selectedMonitor = index;
}
g_config.syncAll = syncAll;
// Keep the shared value in step with whatever the slider now represents,
// so switching modes never jumps the brightness on its own.
MonitorHandleItem* item = ActiveItem();
if (syncAll && item) {
g_config.brightness = item->brightness;
}
SaveConfig();
UpdateTrayIcon();
if (g_hwndFlyout && IsWindowVisible(g_hwndFlyout)) {
InvalidateRect(g_hwndFlyout, NULL, FALSE);
}
}
// -------------------------------------------------------------
// Flyout Slider UI (Windows Volume/Brightness Flyout Style)
// -------------------------------------------------------------
// Flyout size is computed by LayoutFlyout(): it grows when a monitor picker row is needed.
int g_flyoutWidth = 400;
int g_flyoutHeight = 200;
// UI Layout Rectangles (filled in by LayoutFlyout)
const int MAX_MON_BTNS = 9; // [All] + up to 8 monitors
const int PRESET_COUNT = 5;
const int PRESET_VALUES[PRESET_COUNT] = { 0, 25, 50, 75, 100 };
RECT rcResetBtn = {};
RECT rcLangBtnTH = {};
RECT rcLangBtnEN = {};
RECT rcSliderTrack = {};
RECT rcPreset[PRESET_COUNT] = {};
RECT rcAutoStartCheck = {};
RECT rcMonBtn[MAX_MON_BTNS] = {};
int g_monBtnCount = 0; // 0 = single monitor, picker row hidden
int g_sliderRowTop = 0;
int g_titleTop = 11;
int g_hintTop = 33;
// Rebuilds every hit-test / paint rectangle. Called whenever the monitor set changes,
// so the title always owns a full row of its own instead of running under the buttons.
void LayoutFlyout() {
const int W = 400;
const int M = 20; // left / right margin
const int GAP = 6;
g_flyoutWidth = W;
int y = 56;
// Monitor picker row: [All] [1] [2] ... (only when more than one display is attached)
int monCount = (int)g_items.size();
g_monBtnCount = 0;
if (monCount > 1) {
int total = monCount + 1;
if (total > MAX_MON_BTNS) total = MAX_MON_BTNS;
g_monBtnCount = total;
int avail = W - M * 2 - GAP * (total - 1);
int bw = avail / total;
int x = M;
for (int i = 0; i < total; ++i) {
rcMonBtn[i].left = x;
rcMonBtn[i].top = y;
rcMonBtn[i].right = x + bw;
rcMonBtn[i].bottom = y + 26;
x += bw + GAP;
}
y += 34;
}
// Slider row
g_sliderRowTop = y;
rcSliderTrack.left = 54;
rcSliderTrack.top = y + 8;
rcSliderTrack.right = W - 74;
rcSliderTrack.bottom = y + 14;
y += 40;
// Preset buttons
{
int avail = W - M * 2 - GAP * (PRESET_COUNT - 1);
int bw = avail / PRESET_COUNT;
int x = M;
for (int i = 0; i < PRESET_COUNT; ++i) {
rcPreset[i].left = x;
rcPreset[i].top = y;
rcPreset[i].right = x + bw;
rcPreset[i].bottom = y + 28;
x += bw + GAP;
}
y += 40;
}
// Bottom row: autostart on the left, reset + language on the right
rcAutoStartCheck.left = M;
rcAutoStartCheck.top = y;
rcAutoStartCheck.right = M + 185;
rcAutoStartCheck.bottom = y + 24;
rcLangBtnEN.left = W - M - 28; rcLangBtnEN.top = y;
rcLangBtnEN.right = W - M; rcLangBtnEN.bottom = y + 22;
rcLangBtnTH.left = rcLangBtnEN.left - 30; rcLangBtnTH.top = y;
rcLangBtnTH.right = rcLangBtnEN.left - 2; rcLangBtnTH.bottom = y + 22;
rcResetBtn.left = rcLangBtnTH.left - 100; rcResetBtn.top = y;
rcResetBtn.right = rcLangBtnTH.left - 8; rcResetBtn.bottom = y + 22;
g_flyoutHeight = y + 24 + 14;
}
void PositionFlyoutNearTray() {
if (!g_hwndFlyout) return;
RECT workArea;
SystemParametersInfoW(SPI_GETWORKAREA, 0, &workArea, 0);
POINT ptCursor;
GetCursorPos(&ptCursor);
int x = workArea.right - g_flyoutWidth - 12;
int y = workArea.bottom - g_flyoutHeight - 12;
APPBARDATA abd = {};
abd.cbSize = sizeof(APPBARDATA);
if (SHAppBarMessage(ABM_GETTASKBARPOS, &abd)) {
if (abd.uEdge == ABE_BOTTOM) {
y = abd.rc.top - g_flyoutHeight - 10;
x = std::min((long)(workArea.right - g_flyoutWidth - 10), std::max((long)10, (long)(ptCursor.x - g_flyoutWidth / 2)));
} else if (abd.uEdge == ABE_TOP) {
y = abd.rc.bottom + 10;
x = std::min((long)(workArea.right - g_flyoutWidth - 10), std::max((long)10, (long)(ptCursor.x - g_flyoutWidth / 2)));
} else if (abd.uEdge == ABE_LEFT) {
x = abd.rc.right + 10;
y = workArea.bottom - g_flyoutHeight - 10;
} else if (abd.uEdge == ABE_RIGHT) {
x = abd.rc.left - g_flyoutWidth - 10;
y = workArea.bottom - g_flyoutHeight - 10;
}
}
SetWindowPos(g_hwndFlyout, HWND_TOPMOST, x, y, g_flyoutWidth, g_flyoutHeight, SWP_NOACTIVATE | SWP_SHOWWINDOW);
}
void ShowFlyout(bool show) {
if (!g_hwndFlyout) return;
if (show) {
PositionFlyoutNearTray();
ShowWindow(g_hwndFlyout, SW_SHOW);
SetForegroundWindow(g_hwndFlyout);
g_isFlyoutVisible = true;
InvalidateRect(g_hwndFlyout, NULL, FALSE);
} else {
ShowWindow(g_hwndFlyout, SW_HIDE);
g_isFlyoutVisible = false;
}
}
int SliderXFromBrightness(int b) {
int trackLeft = rcSliderTrack.left;
int trackWidth = rcSliderTrack.right - rcSliderTrack.left;
return trackLeft + (int)((b / 100.0f) * trackWidth);
}
int BrightnessFromSliderX(int x) {
int trackLeft = rcSliderTrack.left;
int trackWidth = rcSliderTrack.right - rcSliderTrack.left;
if (x < trackLeft) return 0;
if (x > rcSliderTrack.right) return 100;
float ratio = (float)(x - trackLeft) / (float)trackWidth;
int b = (int)(ratio * 100.0f + 0.5f);
if (b < 0) b = 0;
if (b > 100) b = 100;
return b;
}
void DrawRoundedRect(Graphics& g, Brush* brush, Pen* pen, REAL x, REAL y, REAL w, REAL h, REAL r) {
GraphicsPath path;
path.AddArc(x, y, r * 2, r * 2, 180, 90);
path.AddArc(x + w - r * 2, y, r * 2, r * 2, 270, 90);
path.AddArc(x + w - r * 2, y + h - r * 2, r * 2, r * 2, 0, 90);
path.AddArc(x, y + h - r * 2, r * 2, r * 2, 90, 90);
path.CloseFigure();
if (brush) g.FillPath(brush, &path);
if (pen) g.DrawPath(pen, &path);
}
void DrawBrightnessIcon(Graphics& g, REAL cx, REAL cy, REAL size) {
g.SetSmoothingMode(SmoothingModeAntiAlias);
Pen pen(Color(255, 230, 230, 230), 1.8f);
SolidBrush brush(Color(255, 230, 230, 230));
REAL r = size * 0.28f;
g.FillEllipse(&brush, cx - r, cy - r, r * 2, r * 2);
REAL rayInner = size * 0.42f;
REAL rayOuter = size * 0.58f;
for (int i = 0; i < 8; ++i) {
float angle = i * 45.0f * (3.14159265f / 180.0f);
REAL x1 = cx + cosf(angle) * rayInner;
REAL y1 = cy + sinf(angle) * rayInner;
REAL x2 = cx + cosf(angle) * rayOuter;
REAL y2 = cy + sinf(angle) * rayOuter;
g.DrawLine(&pen, x1, y1, x2, y2);
}
}
LRESULT CALLBACK FlyoutWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
switch (msg) {
case WM_PAINT: {
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
RECT rcClient;
GetClientRect(hwnd, &rcClient);
int w = rcClient.right;
int h = rcClient.bottom;
HDC memDC = CreateCompatibleDC(hdc);
HBITMAP memBmp = CreateCompatibleBitmap(hdc, w, h);
HGDIOBJ oldBmp = SelectObject(memDC, memBmp);
Graphics g(memDC);
g.SetSmoothingMode(SmoothingModeAntiAlias);
g.SetTextRenderingHint(TextRenderingHintClearTypeGridFit);
// Dark background (#202023)
SolidBrush bgBrush(Color(255, 30, 30, 32));
Pen borderPen(Color(255, 60, 60, 65), 1.0f);
DrawRoundedRect(g, &bgBrush, &borderPen, 0.5f, 0.5f, (REAL)w - 1.0f, (REAL)h - 1.0f, 8.0f);
// Fonts
FontFamily fontLeelawadee(L"Leelawadee UI");
FontFamily fontSegoe(L"Segoe UI");
FontFamily* pThaiFont = (fontLeelawadee.GetLastStatus() == Ok) ? &fontLeelawadee : &fontSegoe;
// 1. Header: the title owns the whole first row and is clipped with an
// ellipsis, so long monitor names can never overlap the buttons.
Font titleFont(pThaiFont, 13.5f, FontStyleBold, UnitPixel);
SolidBrush titleBrush(Color(255, 245, 245, 245));
StringFormat titleFormat;
titleFormat.SetAlignment(StringAlignmentNear);
titleFormat.SetLineAlignment(StringAlignmentNear);
titleFormat.SetTrimming(StringTrimmingEllipsisCharacter);
titleFormat.SetFormatFlags(StringFormatFlagsNoWrap);
RectF titleRect(20.0f, (REAL)g_titleTop, (REAL)(w - 40), 20.0f);
g.DrawString(GetStrTitle(), -1, &titleFont, titleRect, &titleFormat, &titleBrush);
// Reset Contrast Button (bottom row, right side)
REAL rstX = (REAL)rcResetBtn.left;
REAL rstY = (REAL)rcResetBtn.top;
REAL rstW = (REAL)(rcResetBtn.right - rcResetBtn.left);
REAL rstH = (REAL)(rcResetBtn.bottom - rcResetBtn.top);
SolidBrush rstBg(Color(255, 45, 45, 48));
Pen rstBorder(Color(255, 75, 75, 80), 1.0f);
SolidBrush rstText(Color(255, 200, 200, 205));
DrawRoundedRect(g, &rstBg, &rstBorder, rstX, rstY, rstW, rstH, 3.0f);
Font rstFont(pThaiFont, 9.5f, FontStyleRegular, UnitPixel);
StringFormat rstFormat;
rstFormat.SetAlignment(StringAlignmentCenter);
rstFormat.SetLineAlignment(StringAlignmentCenter);
RectF rstRect(rstX, rstY, rstW, rstH);
g.DrawString(GetStrResetContrast(), -1, &rstFont, rstRect, &rstFormat, &rstText);
// Language Switcher Buttons: [TH] [EN] (Top Right)
bool isTH = (g_config.lang == Language::TH);
Font langFont(&fontSegoe, 10.0f, FontStyleBold, UnitPixel);
StringFormat langFormat;
langFormat.SetAlignment(StringAlignmentCenter);
langFormat.SetLineAlignment(StringAlignmentCenter);
// TH Button
REAL thX = (REAL)rcLangBtnTH.left;
REAL thY = (REAL)rcLangBtnTH.top;
REAL thW = (REAL)(rcLangBtnTH.right - rcLangBtnTH.left);
REAL thH = (REAL)(rcLangBtnTH.bottom - rcLangBtnTH.top);
SolidBrush thBg(isTH ? Color(255, 0, 120, 215) : Color(255, 45, 45, 48));
Pen thBorder(isTH ? Color(255, 0, 150, 255) : Color(255, 70, 70, 75), 1.0f);
SolidBrush thText(isTH ? Color(255, 255, 255, 255) : Color(255, 170, 170, 175));
DrawRoundedRect(g, &thBg, &thBorder, thX, thY, thW, thH, 3.0f);
RectF thRect(thX, thY, thW, thH);
g.DrawString(L"TH", -1, &langFont, thRect, &langFormat, &thText);
// EN Button
REAL enX = (REAL)rcLangBtnEN.left;
REAL enY = (REAL)rcLangBtnEN.top;
REAL enW = (REAL)(rcLangBtnEN.right - rcLangBtnEN.left);
REAL enH = (REAL)(rcLangBtnEN.bottom - rcLangBtnEN.top);
SolidBrush enBg(!isTH ? Color(255, 0, 120, 215) : Color(255, 45, 45, 48));
Pen enBorder(!isTH ? Color(255, 0, 150, 255) : Color(255, 70, 70, 75), 1.0f);
SolidBrush enText(!isTH ? Color(255, 255, 255, 255) : Color(255, 170, 170, 175));
DrawRoundedRect(g, &enBg, &enBorder, enX, enY, enW, enH, 3.0f);
RectF enRect(enX, enY, enW, enH);
g.DrawString(L"EN", -1, &langFont, enRect, &langFormat, &enText);
// Hotkey hint + contrast baseline, also clipped to the row width
Font tipFont(pThaiFont, 10.5f, FontStyleRegular, UnitPixel);
SolidBrush tipBrush(Color(255, 140, 140, 145));
StringFormat tipFormat;
tipFormat.SetTrimming(StringTrimmingEllipsisCharacter);
tipFormat.SetFormatFlags(StringFormatFlagsNoWrap);
std::wstring tipStr = std::wstring(GetStrHotkeys()) + L" (Base Contrast: " + std::to_wstring(g_config.baseContrast) + L")";
RectF tipRect(20.0f, (REAL)g_hintTop, (REAL)(w - 40), 18.0f);
g.DrawString(tipStr.c_str(), -1, &tipFont, tipRect, &tipFormat, &tipBrush);
// 2. Monitor picker row: [All] [1] [2] ...
if (g_monBtnCount > 0) {
Font monFont(pThaiFont, 11.0f, FontStyleRegular, UnitPixel);
StringFormat monFormat;
monFormat.SetAlignment(StringAlignmentCenter);
monFormat.SetLineAlignment(StringAlignmentCenter);
monFormat.SetTrimming(StringTrimmingEllipsisCharacter);
monFormat.SetFormatFlags(StringFormatFlagsNoWrap);
for (int i = 0; i < g_monBtnCount; ++i) {
bool isAll = (i == 0);
bool active = isAll ? g_config.syncAll
: (!g_config.syncAll && g_config.selectedMonitor == i - 1);
SolidBrush mBg(active ? Color(255, 0, 120, 215) : Color(255, 46, 46, 50));
Pen mBorder(active ? Color(255, 0, 150, 255) : Color(255, 70, 70, 76), 1.0f);
SolidBrush mText(active ? Color(255, 255, 255, 255) : Color(255, 205, 205, 210));
REAL mx = (REAL)rcMonBtn[i].left;
REAL my = (REAL)rcMonBtn[i].top;
REAL mw = (REAL)(rcMonBtn[i].right - rcMonBtn[i].left);
REAL mh = (REAL)(rcMonBtn[i].bottom - rcMonBtn[i].top);
DrawRoundedRect(g, &mBg, &mBorder, mx, my, mw, mh, 4.0f);
std::wstring monLabel = isAll
? std::wstring(GetStrAllMonitors())
: (std::wstring(GetStrMonitorShort()) + L" " + std::to_wstring(i));
RectF mRect(mx + 2.0f, my, mw - 4.0f, mh);
g.DrawString(monLabel.c_str(), -1, &monFont, mRect, &monFormat, &mText);
}
}
// 3. Slider Row
REAL rowTop = (REAL)g_sliderRowTop;
DrawBrightnessIcon(g, 30.0f, rowTop + 11.0f, 22.0f);
REAL trackY = (REAL)rcSliderTrack.top + 1.0f;
REAL trackH = 4.0f;
REAL trackX = (REAL)rcSliderTrack.left;
REAL trackW = (REAL)(rcSliderTrack.right - rcSliderTrack.left);
// Track background
SolidBrush trackBgBrush(Color(255, 75, 75, 80));
DrawRoundedRect(g, &trackBgBrush, NULL, trackX, trackY, trackW, trackH, 2.0f);
// Active Track (Windows Blue #0078D7)
int thumbX = SliderXFromBrightness(GetTargetBrightness());
REAL fillW = (REAL)(thumbX - trackX);
if (fillW > 0) {
SolidBrush fillBrush(Color(255, 0, 120, 215));
DrawRoundedRect(g, &fillBrush, NULL, trackX, trackY, fillW, trackH, 2.0f);
}
// Slider Thumb handle
SolidBrush thumbBrush(Color(255, 0, 120, 215));
Pen thumbBorder(Color(255, 255, 255, 255), 2.0f);
g.FillEllipse(&thumbBrush, thumbX - 8.0f, trackY + 2.0f - 8.0f, 16.0f, 16.0f);
g.DrawEllipse(&thumbBorder, thumbX - 8.0f, trackY + 2.0f - 8.0f, 16.0f, 16.0f);
// Percentage Number (Right)
Font pctFont(&fontSegoe, 16.5f, FontStyleBold, UnitPixel);
SolidBrush pctBrush(Color(255, 255, 255, 255));
StringFormat pctFormat;
pctFormat.SetAlignment(StringAlignmentFar);
pctFormat.SetLineAlignment(StringAlignmentCenter);
RectF pctRect((REAL)rcSliderTrack.right + 8.0f, rowTop - 2.0f, 56.0f, 26.0f);
std::wstring pctStr = std::to_wstring(GetTargetBrightness());
g.DrawString(pctStr.c_str(), -1, &pctFont, pctRect, &pctFormat, &pctBrush);
// 4. Preset Buttons: [0%] [25%] [50%] [75%] [100%]
Font btnFont(&fontSegoe, 11.5f, FontStyleRegular, UnitPixel);
StringFormat btnFormat;
btnFormat.SetAlignment(StringAlignmentCenter);
btnFormat.SetLineAlignment(StringAlignmentCenter);
int shownBrightness = GetTargetBrightness();
for (int i = 0; i < PRESET_COUNT; ++i) {
bool isCurrent = (shownBrightness == PRESET_VALUES[i]);
SolidBrush btnBg(isCurrent ? Color(255, 0, 120, 215) : Color(255, 46, 46, 50));
Pen btnBorder(isCurrent ? Color(255, 0, 150, 255) : Color(255, 70, 70, 76), 1.0f);
SolidBrush btnText(isCurrent ? Color(255, 255, 255, 255) : Color(255, 215, 215, 215));
REAL bx = (REAL)rcPreset[i].left;
REAL by = (REAL)rcPreset[i].top;
REAL bw = (REAL)(rcPreset[i].right - rcPreset[i].left);
REAL bh = (REAL)(rcPreset[i].bottom - rcPreset[i].top);
DrawRoundedRect(g, &btnBg, &btnBorder, bx, by, bw, bh, 4.0f);
std::wstring btnLabel = std::to_wstring(PRESET_VALUES[i]) + L"%";
RectF bRect(bx, by, bw, bh);
g.DrawString(btnLabel.c_str(), -1, &btnFont, bRect, &btnFormat, &btnText);
}
// 5. Checkbox: AutoStart
Font checkFont(pThaiFont, 11.5f, FontStyleRegular, UnitPixel);
SolidBrush checkText(Color(255, 230, 230, 230));
REAL cbX1 = (REAL)rcAutoStartCheck.left;
REAL cbY1 = (REAL)rcAutoStartCheck.top + 4.0f;
SolidBrush cbBg1(g_config.autoStart ? Color(255, 0, 120, 215) : Color(255, 46, 46, 50));
Pen cbBorder1(Color(255, 95, 95, 100), 1.0f);
DrawRoundedRect(g, &cbBg1, &cbBorder1, cbX1, cbY1, 15.0f, 15.0f, 3.0f);
if (g_config.autoStart) {
Pen checkPen(Color(255, 255, 255, 255), 2.0f);
g.DrawLine(&checkPen, cbX1 + 3.5f, cbY1 + 7.5f, cbX1 + 6.5f, cbY1 + 11.0f);
g.DrawLine(&checkPen, cbX1 + 6.5f, cbY1 + 11.0f, cbX1 + 11.5f, cbY1 + 4.0f);
}
PointF cbTextPt1(cbX1 + 22.0f, (REAL)rcAutoStartCheck.top + 3.0f);
g.DrawString(GetStrAutoStart(), -1, &checkFont, cbTextPt1, &checkText);
// Blit to screen
BitBlt(hdc, 0, 0, w, h, memDC, 0, 0, SRCCOPY);
SelectObject(memDC, oldBmp);
DeleteObject(memBmp);
DeleteDC(memDC);
EndPaint(hwnd, &ps);
return 0;
}
case WM_LBUTTONDOWN: {
POINT pt = { (short)LOWORD(lParam), (short)HIWORD(lParam) };
// Monitor picker click: index 0 is "all monitors", the rest are one display each
for (int i = 0; i < g_monBtnCount; ++i) {
if (PtInRect(&rcMonBtn[i], pt)) {
SetTargetMode(i == 0, i - 1);
return 0;
}
}
// Reset Contrast Button click
if (PtInRect(&rcResetBtn, pt)) {
ResetBaseContrast();
return 0;
}
// Language Buttons click
if (PtInRect(&rcLangBtnTH, pt)) {
SetLanguage(Language::TH);
return 0;
}
if (PtInRect(&rcLangBtnEN, pt)) {
SetLanguage(Language::EN);
return 0;
}
// Click on slider area
if (pt.x >= rcSliderTrack.left - 10 && pt.x <= rcSliderTrack.right + 10 &&
pt.y >= rcSliderTrack.top - 18 && pt.y <= rcSliderTrack.bottom + 18) {