-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathProgram.Config.cs
More file actions
991 lines (900 loc) · 40.9 KB
/
Program.Config.cs
File metadata and controls
991 lines (900 loc) · 40.9 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
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using Microsoft.Win32;
using Microsoft.Win32.TaskScheduler;
using Newtonsoft.Json.Linq;
using static OmenSuperHub.GpuAppManager;
using static OmenSuperHub.OmenHardware;
namespace OmenSuperHub {
static partial class Program {
/// <summary>
/// 获取当前系统 UI 语言对应的语言代码(zh-CN / zh-TW / en)
/// 若无法匹配,返回 "en"
/// </summary>
private static string GetSystemLanguage() {
string cultureName = CultureInfo.CurrentUICulture.Name;
// 简体中文:zh-CN, zh-Hans, zh-SG 等
if (cultureName.StartsWith("zh-Hans", StringComparison.OrdinalIgnoreCase) ||
cultureName.Equals("zh-CN", StringComparison.OrdinalIgnoreCase) ||
cultureName.Equals("zh-SG", StringComparison.OrdinalIgnoreCase)) {
return "zh-CN";
}
// 繁体中文:zh-TW, zh-HK, zh-MO, zh-Hant 等
if (cultureName.StartsWith("zh-Hant", StringComparison.OrdinalIgnoreCase) ||
cultureName.Equals("zh-TW", StringComparison.OrdinalIgnoreCase) ||
cultureName.Equals("zh-HK", StringComparison.OrdinalIgnoreCase) ||
cultureName.Equals("zh-MO", StringComparison.OrdinalIgnoreCase)) {
return "zh-TW";
}
// 英语:en, en-US, en-GB 等
if (cultureName.StartsWith("en", StringComparison.OrdinalIgnoreCase)) {
return "en";
}
// 其他语言默认英语
return "en";
}
static void LoadLanguageSetting() {
try {
using (RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\OmenSuperHub")) {
if (key != null) {
// 注册表中有保存的语言 → 使用保存的值
string savedLang = (string)key.GetValue("AppLanguage", null);
if (!string.IsNullOrEmpty(savedLang)) {
appLanguage = savedLang;
} else {
// 首次运行,无注册表值 → 使用系统语言
appLanguage = GetSystemLanguage();
// 可选:立即将系统语言写入注册表,避免下次启动再检测
SaveConfig("AppLanguage");
}
} else {
// 注册表键不存在(全新安装)→ 使用系统语言
appLanguage = GetSystemLanguage();
SaveConfig("AppLanguage"); // 保存,让后续启动直接使用该值
}
}
} catch { }
ApplyLanguage(appLanguage);
}
static void ApplyLanguage(string lang) {
switch (lang) {
case "zh-TW": Strings.Current = AppLanguage.TraditionalChinese; break;
case "en": Strings.Current = AppLanguage.English; break;
default: Strings.Current = AppLanguage.SimplifiedChinese; break;
}
}
// 任务计划程序
static void AutoStartEnable() {
string currentPath = AppDomain.CurrentDomain.BaseDirectory;
string exePath = Path.Combine(currentPath, "OmenSuperHub.exe");
using (TaskService ts = new TaskService()) {
// ── 任务一:系统启动时以 SYSTEM 账户启动 ──────────────────────────
TaskDefinition tdBoot = ts.NewTask();
tdBoot.RegistrationInfo.Description = "Start OmenSuperHub at system boot";
tdBoot.Principal.RunLevel = TaskRunLevel.Highest;
tdBoot.Principal.UserId = "SYSTEM";
tdBoot.Principal.LogonType = TaskLogonType.ServiceAccount;
tdBoot.Actions.Add(new ExecAction(exePath, null, null));
BootTrigger bootTrigger = new BootTrigger();
// bootTrigger.Delay = TimeSpan.FromSeconds(10); // 可选:延迟启动
tdBoot.Triggers.Add(bootTrigger);
tdBoot.Settings.DisallowStartIfOnBatteries = false;
tdBoot.Settings.StopIfGoingOnBatteries = false;
tdBoot.Settings.ExecutionTimeLimit = TimeSpan.Zero;
tdBoot.Settings.AllowHardTerminate = false;
ts.RootFolder.RegisterTaskDefinition(@"OmenSuperHub", tdBoot);
//Console.WriteLine("任务一已创建:系统启动时运行。");
// ── 任务二:用户登录时重启────────────────────────
TaskDefinition tdLogon = ts.NewTask();
tdLogon.RegistrationInfo.Description = "Restart OmenSuperHub at user logon";
tdLogon.Principal.RunLevel = TaskRunLevel.Highest;
tdLogon.Actions.Add(new ExecAction(
exePath,
"--relaunch", // 传入参数,触发静默重启逻辑
null
));
LogonTrigger logonTrigger = new LogonTrigger();
tdLogon.Triggers.Add(logonTrigger);
tdLogon.Settings.Hidden = true; // 任务本身也隐藏
tdLogon.Settings.DisallowStartIfOnBatteries = false;
tdLogon.Settings.StopIfGoingOnBatteries = false;
tdLogon.Settings.ExecutionTimeLimit = TimeSpan.Zero;
tdLogon.Settings.AllowHardTerminate = false;
ts.RootFolder.RegisterTaskDefinition(@"OmenSuperHub_Logon", tdLogon);
//Console.WriteLine("任务二已创建:用户登录时重启。");
}
CleanUpAndRemoveTasks();
}
static void AutoStartDisable() {
using (TaskService ts = new TaskService()) {
string[] taskNames = { "OmenSuperHub", "OmenSuperHub_Logon" };
foreach (string taskName in taskNames) {
Task existingTask = ts.FindTask(taskName);
if (existingTask != null) {
ts.RootFolder.DeleteTask(taskName);
//Console.WriteLine($"任务 {taskName} 已删除。");
} else {
//Console.WriteLine($"任务 {taskName} 不存在,无需删除。");
}
}
}
}
// 清理旧版自启
public static void CleanUpAndRemoveTasks() {
// 目标文件夹和文件定义
string targetFolder = @"C:\Program Files\OmenSuperHub";
string taskName = "Omen Boot";
string file1 = @"C:\Windows\SysWOW64\silent.txt";
string file2 = @"C:\Windows\SysWOW64\cool.txt";
// 删除目标文件夹及其内容
if (Directory.Exists(targetFolder)) {
string command = $"rd /s /q \"{targetFolder}\"";
var result = ExecuteCommand(command);
//Console.WriteLine(result.Output);
} else {
//Console.WriteLine("旧文件夹不存在");
}
// 删除 file1
if (File.Exists(file1)) {
string command = $"del /f /q \"{file1}\"";
var result = ExecuteCommand(command);
//Console.WriteLine($"文件已删除: {file1}");
//Console.WriteLine(result.Output);
} else {
//Console.WriteLine($"文件不存在: {file1}");
}
// 删除 file2
if (File.Exists(file2)) {
string command = $"del /f /q \"{file2}\"";
var result = ExecuteCommand(command);
//Console.WriteLine($"文件已删除: {file2}");
//Console.WriteLine(result.Output);
} else {
//Console.WriteLine($"文件不存在: {file2}");
}
// 检查并删除计划任务
string taskQueryCommand = $"schtasks /query /tn \"{taskName}\"";
var taskQueryResult = ExecuteCommand(taskQueryCommand);
if (taskQueryResult.ExitCode == 0) {
string deleteTaskCommand = $"schtasks /delete /tn \"{taskName}\" /f";
var deleteTaskResult = ExecuteCommand(deleteTaskCommand);
//Console.WriteLine("已成功删除计划任务 \"Omen Boot\"。");
//Console.WriteLine(deleteTaskResult.Output);
} else {
//Console.WriteLine($"计划任务 \"{taskName}\" 不存在。");
}
// 从注册表中删除开机自启项
string regDeleteCommand = @"reg delete ""HKLM\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Run"" /v ""OmenSuperHub"" /f";
var regDeleteResult = ExecuteCommand(regDeleteCommand);
//Console.WriteLine("成功取消开机自启");
//Console.WriteLine(regDeleteResult.Output);
}
static void RestoreCPUPower() {
// 恢复CPU功耗设定
if (cpuPower.Contains(" W")) {
int value = int.Parse(cpuPower.Replace(" W", "").Trim());
if (value >= 10 && value <= 254) {
SetCpuPowerLimit((byte)value);
}
}
}
static void RestorePowerConfig() {
SetUnleashMode();
System.Threading.Tasks.Task.Delay(1000).ContinueWith(_ => {
RestoreCPUPower();
SetGpuPowerState(tgpPower == "on", ppabPower == "on", dState == "normal" ? 1 : 2);
if (tppPower.Contains(" W")) {
int value = int.Parse(tppPower.Replace(" W", "").Trim());
if (value >= 20 && value <= 254) {
SetConcurrentTdp((byte)value);
}
}
});
}
static void RestoreFanControl() {
if (fanControl == "auto") {
SetMaxFanSpeedOff();
fanControlTimer.Change(0, 1000);
UpdateCheckedState("fanControlGroup", Strings.FanAuto);
} else if (fanControl.Contains("max")) {
SetMaxFanSpeedOn();
fanControlTimer.Change(Timeout.Infinite, Timeout.Infinite);
UpdateCheckedState("fanControlGroup", Strings.FanMax);
} else if (fanControl.Contains(" RPM")) {
SetMaxFanSpeedOff();
fanControlTimer.Change(Timeout.Infinite, Timeout.Infinite);
int rpmValue = int.Parse(fanControl.Replace(" RPM", "").Trim());
SetFanLevel(rpmValue / 100, rpmValue / 100, Is3FanNb);
if (fanTrackBar != null && rpmValue / 100 >= fanTrackBar.Minimum && rpmValue / 100 <= fanTrackBar.Maximum) {
fanTrackBar.Value = rpmValue / 100;
}
UpdateCheckedState("fanControlGroup", Strings.SetFanSpeedSlider);
}
}
static void InitMaxTemp() {
maxCPUTemp = null;
if (platformSettings != null) {
int throttle = platformSettings.temperatureThrottlingPerformance;
if (throttle > 0) {
maxCPUTemp = throttle;
}
if (hasNVIDIAGpu) {
throttle = GetGpuTemperatureTarget();
if (throttle > 50) {
maxGPUTemp = throttle;
}
}
}
}
// 从 platformSettings 提取平台最大转速,独立于风扇配置加载,启动时调用一次
static void InitPlatformMaxFanSpeed() {
if (platformSettings == null) return;
int? maxFanSpeed = null;
var candidates = new[] {
platformSettings.SwFanControlCustomDefault,
platformSettings.SwFanControlCustomPerformance,
platformSettings.SwFanControlCustomUnleashed
};
foreach (var fanCustom in candidates) {
if (fanCustom?.FanTable == null) continue;
var cpuSpeeds = fanCustom.FanTable.Fan_Table_CPU_Fan_Speed_List;
var gpuSpeeds = fanCustom.FanTable.Fan_Table_GPU_Fan_Speed_List;
if (cpuSpeeds != null)
foreach (var v in cpuSpeeds)
if (!maxFanSpeed.HasValue || v > maxFanSpeed.Value) maxFanSpeed = v;
if (gpuSpeeds != null)
foreach (var v in gpuSpeeds)
if (!maxFanSpeed.HasValue || v > maxFanSpeed.Value) maxFanSpeed = v;
}
if (maxFanSpeed.HasValue)
platformMaxFanSpeed = maxFanSpeed.Value * 100;
}
static void LoadDefaultFanConfig(string filePath) {
// ── 1. 获取 CPU 与 GPU 的允许最高温度差 ─────────────────────
int? tempDelta = null;
int maxGPUT = 87;
if (maxGPUTemp.HasValue) {
maxGPUT = maxGPUTemp.Value;
}
if (maxCPUTemp.HasValue) {
tempDelta = maxCPUTemp.Value - maxGPUT;
}
// ── 2. 若两个值均获取成功,则生成 silent / cool 转速表 ──────────────
if (platformMaxFanSpeed.HasValue && maxCPUTemp.HasValue && tempDelta.HasValue) {
int maxRpm = platformMaxFanSpeed.Value;
int maxCpu = maxCPUTemp.Value;
int delta = tempDelta.Value;
List<int> cpuTempList, cpuSpeedList, gpuTempList, gpuSpeedList;
bool isSilent = filePath.IndexOf("silent", StringComparison.OrdinalIgnoreCase) >= 0;
if (isSilent) {
// silent: cpu30/gpu20 → 0RPM, 60℃ → maxRpm/3, 87℃ → maxRpm*2/3, maxTemp → maxRpm
cpuTempList = new List<int> { 30, 60, 87, maxCpu };
cpuSpeedList = new List<int> { 0, maxRpm / 3, maxRpm * 2 / 3, maxRpm - maxRpm / 10 };
gpuTempList = new List<int> { 30 - delta, 60 - delta, 87 - delta, maxGPUT };
gpuSpeedList = new List<int> { 0, maxRpm / 3, maxRpm * 2 / 3, maxRpm - maxRpm / 10 };
} else {
// cool: cpu45/gpu35 → maxRpm/4, (maxTemp-5)℃ → maxRpm
cpuTempList = new List<int> { 45, maxCpu - 5, maxCpu };
cpuSpeedList = new List<int> { maxRpm / 4, maxRpm, maxRpm + maxRpm / 10 };
gpuTempList = new List<int> { 45 - delta, maxGPUT - 5, maxGPUT };
gpuSpeedList = new List<int> { maxRpm / 4, maxRpm, maxRpm + maxRpm / 10 };
}
// 写入文件
var lines = new List<string> {
"Fan_Table_CPU_Temperature_List=" + string.Join(",", cpuTempList),
"Fan_Table_CPU_Fan_Speed_List=" + string.Join(",", cpuSpeedList),
"Fan_Table_GPU_Temperature_List=" + string.Join(",", gpuTempList),
"Fan_Table_GPU_Fan_Speed_List=" + string.Join(",", gpuSpeedList)
};
File.WriteAllLines(filePath, lines);
LoadFanConfigFromLists(cpuTempList, cpuSpeedList, gpuTempList, gpuSpeedList);
return;
}
// ── 3. 兜底:无法提取参数时使用硬编码默认值 ─────────────────────────
GenerateDefaultMapping(filePath);
}
static void LoadFanConfig(string filePath) {
string absoluteFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, filePath);
if (!File.Exists(absoluteFilePath)) {
//Logger.Info($"{absoluteFilePath} not found.");
LoadDefaultFanConfig(absoluteFilePath);
return;
}
string[] allLines = File.ReadAllLines(absoluteFilePath);
if (allLines.Length == 0) {
LoadDefaultFanConfig(absoluteFilePath);
return;
}
// 判断文件格式:若第一行包含'='则视为新格式,否则为旧CSV格式
bool isNewFormat = allLines[0].Contains('=');
if (isNewFormat) {
var cpuTempList = new List<int>();
var cpuSpeedList = new List<int>();
var gpuTempList = new List<int>();
var gpuSpeedList = new List<int>();
foreach (string line in allLines) {
if (string.IsNullOrWhiteSpace(line)) continue;
int eqIdx = line.IndexOf('=');
if (eqIdx < 0) continue;
string key = line.Substring(0, eqIdx).Trim();
string valueStr = line.Substring(eqIdx + 1).Trim();
var values = valueStr.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Select(s => int.Parse(s.Trim()))
.ToList();
switch (key) {
case "Fan_Table_CPU_Temperature_List":
cpuTempList = values;
break;
case "Fan_Table_CPU_Fan_Speed_List":
cpuSpeedList = values;
break;
case "Fan_Table_GPU_Temperature_List":
gpuTempList = values;
break;
case "Fan_Table_GPU_Fan_Speed_List":
gpuSpeedList = values;
break;
}
}
// 校验数据完整性
if (cpuTempList.Count == 0 || cpuSpeedList.Count == 0 ||
gpuTempList.Count == 0 || gpuSpeedList.Count == 0 ||
cpuTempList.Count != cpuSpeedList.Count ||
gpuTempList.Count != gpuSpeedList.Count) {
Logger.Error($"{absoluteFilePath} invalid new format, regenerating.");
LoadDefaultFanConfig(absoluteFilePath);
return;
}
LoadFanConfigFromLists(cpuTempList, cpuSpeedList, gpuTempList, gpuSpeedList);
} else {
// 旧格式:CPU,Fan1,Fan2,GPU,Fan1,Fan2 多行
var cpuTempList = new List<int>();
var cpuSpeedList = new List<int>();
var gpuTempList = new List<int>();
var gpuSpeedList = new List<int>();
try {
for (int i = 1; i < allLines.Length; i++) // 跳过标题行
{
var parts = allLines[i].Split(',');
if (parts.Length < 6) continue;
int cpuTemp = int.Parse(parts[0].Trim());
int cpuFan1 = int.Parse(parts[1].Trim()); // 我们取Fan1作为统一速度
int gpuTemp = int.Parse(parts[3].Trim());
int gpuFan1 = int.Parse(parts[4].Trim());
cpuTempList.Add(cpuTemp);
cpuSpeedList.Add(cpuFan1);
gpuTempList.Add(gpuTemp);
gpuSpeedList.Add(gpuFan1);
}
} catch {
Logger.Error($"{absoluteFilePath} parse error, regenerating.");
LoadDefaultFanConfig(absoluteFilePath);
return;
}
if (cpuTempList.Count == 0 || gpuTempList.Count == 0) {
LoadDefaultFanConfig(absoluteFilePath);
return;
}
// 将旧格式转换为新格式并覆盖写入
var newLines = new List<string>
{
"Fan_Table_CPU_Temperature_List=" + string.Join(",", cpuTempList),
"Fan_Table_CPU_Fan_Speed_List=" + string.Join(",", cpuSpeedList),
"Fan_Table_GPU_Temperature_List=" + string.Join(",", gpuTempList),
"Fan_Table_GPU_Fan_Speed_List=" + string.Join(",", gpuSpeedList)
};
File.WriteAllLines(absoluteFilePath, newLines);
LoadFanConfigFromLists(cpuTempList, cpuSpeedList, gpuTempList, gpuSpeedList);
}
}
// Generate default temperature-fan speed mapping
static void GenerateDefaultMapping(string filePath) {
// 硬编码默认映射(与原逻辑一致,转换为新格式)
var cpuTempList = new List<int> { 50, 60, 85, 100 };
var cpuSpeedList = new List<int> { 1600, 2000, 4000, 5600 }; // RPM
var gpuTempList = new List<int> { 40, 50, 75, 90 };
var gpuSpeedList = new List<int> { 1600, 2000, 4000, 5600 };
var lines = new List<string>
{
"Fan_Table_CPU_Temperature_List=" + string.Join(",", cpuTempList),
"Fan_Table_CPU_Fan_Speed_List=" + string.Join(",", cpuSpeedList),
"Fan_Table_GPU_Temperature_List=" + string.Join(",", gpuTempList),
"Fan_Table_GPU_Fan_Speed_List=" + string.Join(",", gpuSpeedList)
};
File.WriteAllLines(filePath, lines);
LoadFanConfigFromLists(cpuTempList, cpuSpeedList, gpuTempList, gpuSpeedList);
}
static void LoadFanConfigFromLists(List<int> cpuTempList, List<int> cpuSpeedList,
List<int> gpuTempList, List<int> gpuSpeedList) {
lock (CPUTempFanMap) {
CPUTempFanMap.Clear();
GPUTempFanMap.Clear();
for (int i = 0; i < cpuTempList.Count; i++) {
int speedRpm = cpuSpeedList[i];
CPUTempFanMap[cpuTempList[i]] = new List<int> { speedRpm, speedRpm }; // 双风扇同速
}
for (int i = 0; i < gpuTempList.Count; i++) {
int speedRpm = gpuSpeedList[i];
GPUTempFanMap[gpuTempList[i]] = new List<int> { speedRpm, speedRpm };
}
}
}
// Get fan speed for CPU and GPU and return the maximum
// 使用平滑后的温度查表,保证高中低档响应速度生效;实时档下平滑温度==原始温度
// 只有对应监控开启且温度已完成初始化时,才参与风扇转速计算
static int GetFanSpeedForTemperature(int fanIndex) {
if (CPUTempFanMap.Count == 0 || GPUTempFanMap.Count == 0) return 0;
int resultSpeed = 0;
if (monitorCPU && cpuTempReady) {
int cpuFanSpeed = GetFanSpeedForSpecificTemperature(smoothedCPUTemp, CPUTempFanMap, fanIndex);
resultSpeed = Math.Max(resultSpeed, cpuFanSpeed);
}
if (monitorGPU && gpuTempReady) {
int gpuFanSpeed = GetFanSpeedForSpecificTemperature(smoothedGPUTemp, GPUTempFanMap, fanIndex);
resultSpeed = Math.Max(resultSpeed, gpuFanSpeed);
}
return resultSpeed;
}
static void SaveConfig(string configName = null) {
try {
using (RegistryKey key = Registry.CurrentUser.CreateSubKey(@"Software\OmenSuperHub")) {
if (key != null) {
if (configName == null) {
key.SetValue("FanTable", fanTable);
key.SetValue("FanControl", fanControl);
key.SetValue("TempSensitivity", tempSensitivity);
key.SetValue("CpuPower", cpuPower);
key.SetValue("TgpPower", tgpPower);
key.SetValue("PpabPower", ppabPower);
key.SetValue("DState", dState);
if (hasNVIDIAGpu) {
key.SetValue("GpuClock", gpuClock);
key.SetValue("DBVersion", DBVersion);
}
key.SetValue("AutoStart", autoStart);
key.SetValue("AlreadyRead", alreadyRead);
key.SetValue("CustomIcon", customIcon);
key.SetValue("OmenKey", omenKey);
if (hasNVIDIAGpu || hasAMDDiscreteGpu)
key.SetValue("MonitorGPU", monitorGPU);
key.SetValue("MonitorCPU", monitorCPU);
key.SetValue("MonitorFan", monitorFan);
key.SetValue("MonitorRefreshRate", monitorRefreshRate);
key.SetValue("TempDisplayMode", tempDisplayMode);
key.SetValue("FloatingBarLoc", floatingBarLoc);
key.SetValue("FloatingBar", floatingBar);
key.SetValue("DataLocalize", dataLocalize);
key.SetValue("AppLanguage", appLanguage);
key.SetValue("TppPower", tppPower);
//key.SetValue("PL4Power", powerLimit4);
key.SetValue("IccMax", iccMax);
key.SetValue("AcLoadLine", acLoadline);
} else {
switch (configName) {
case "FanTable":
key.SetValue("FanTable", fanTable);
break;
case "FanControl":
key.SetValue("FanControl", fanControl);
break;
case "TempSensitivity":
key.SetValue("TempSensitivity", tempSensitivity);
break;
case "CpuPower":
key.SetValue("CpuPower", cpuPower);
break;
case "TgpPower":
key.SetValue("TgpPower", tgpPower);
break;
case "PpabPower":
key.SetValue("PpabPower", ppabPower);
break;
case "DState":
key.SetValue("DState", dState);
break;
case "GpuClock":
key.SetValue("GpuClock", gpuClock);
break;
case "DBVersion":
key.SetValue("DBVersion", DBVersion);
break;
case "AutoStart":
key.SetValue("AutoStart", autoStart);
break;
case "AlreadyRead":
key.SetValue("AlreadyRead", alreadyRead);
break;
case "CustomIcon":
key.SetValue("CustomIcon", customIcon);
break;
case "OmenKey":
key.SetValue("OmenKey", omenKey);
break;
case "MonitorGPU":
key.SetValue("MonitorGPU", monitorGPU);
break;
case "MonitorCPU":
key.SetValue("MonitorCPU", monitorCPU);
break;
case "MonitorFan":
key.SetValue("MonitorFan", monitorFan);
break;
case "MonitorRefreshRate":
key.SetValue("MonitorRefreshRate", monitorRefreshRate);
break;
case "TempDisplayMode":
key.SetValue("TempDisplayMode", tempDisplayMode);
break;
case "FloatingBarSize":
key.SetValue("FloatingBarSize", textSize);
break;
case "FloatingBarLoc":
key.SetValue("FloatingBarLoc", floatingBarLoc);
break;
case "FloatingBar":
key.SetValue("FloatingBar", floatingBar);
break;
case "DataLocalize":
key.SetValue("DataLocalize", dataLocalize);
break;
case "TppPower":
key.SetValue("TppPower", tppPower);
break;
case "PL4Power":
//key.SetValue("PL4Power", powerLimit4);
break;
case "IccMax":
key.SetValue("IccMax", iccMax);
break;
case "AcLoadLine":
key.SetValue("AcLoadLine", acLoadline);
break;
case "AppLanguage":
key.SetValue("AppLanguage", appLanguage);
break;
}
}
}
}
} catch (Exception ex) {
Logger.Error($"Error saving configuration: {ex.Message}");
}
}
static void RestoreConfig() {
try {
using (RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\OmenSuperHub")) {
if (key != null) {
fanTable = (string)key.GetValue("FanTable", "cool");
if (fanTable.Contains("cool")) {
LoadFanConfig("cool.txt");
UpdateCheckedState("fanTableGroup", Strings.FanCoolMode);
} else if (fanTable.Contains("silent")) {
LoadFanConfig("silent.txt");
UpdateCheckedState("fanTableGroup", Strings.FanSilentMode);
}
fanControl = (string)key.GetValue("FanControl", "auto");
if (fanControl == "auto") {
SetMaxFanSpeedOff();
fanControlTimer.Change(0, 1000);
UpdateCheckedState("fanControlGroup", Strings.FanAuto);
} else if (fanControl.Contains("max")) {
SetMaxFanSpeedOn();
fanControlTimer.Change(Timeout.Infinite, Timeout.Infinite);
UpdateCheckedState("fanControlGroup", Strings.FanMax);
} else if (fanControl.Contains(" RPM")) {
SetMaxFanSpeedOff();
fanControlTimer.Change(Timeout.Infinite, Timeout.Infinite);
int rpmValue = int.Parse(fanControl.Replace(" RPM", "").Trim());
SetFanLevel(rpmValue / 100, rpmValue / 100, Is3FanNb);
if (fanTrackBar != null && rpmValue / 100 >= fanTrackBar.Minimum && rpmValue / 100 <= fanTrackBar.Maximum) {
fanTrackBar.Value = rpmValue / 100;
}
UpdateCheckedState("fanControlGroup", Strings.SetFanSpeedSlider);
}
tempSensitivity = (string)key.GetValue("TempSensitivity", "high");
switch (tempSensitivity) {
case "realtime":
respondSpeed = 1;
UpdateCheckedState("tempSensitivityGroup", Strings.FanRespRealtime);
break;
case "high":
respondSpeed = 0.4f;
UpdateCheckedState("tempSensitivityGroup", Strings.FanRespHigh);
break;
case "medium":
respondSpeed = 0.1f;
UpdateCheckedState("tempSensitivityGroup", Strings.FanRespMedium);
break;
case "low":
respondSpeed = 0.04f;
UpdateCheckedState("tempSensitivityGroup", Strings.FanRespLow);
break;
}
tppPower = (string)key.GetValue("TppPower", "null");
// TPP 设置单独延迟 1s 应用,避免启动时与其他设置冲突
{
string tppPowerSnapshot = tppPower;
System.Threading.Tasks.Task.Delay(1000).ContinueWith(_ => {
if (tppPowerSnapshot == "null") {
UpdateCheckedState("tppPowerGroup", Strings.NotSet);
} else if (tppPowerSnapshot == "max") {
SetConcurrentTdp(254);
if (tppTrackBar != null && tppTrackBar.Minimum <= 254 && 254 <= tppTrackBar.Maximum) {
tppTrackBar.Value = 254;
}
} else if (tppPowerSnapshot.Contains(" W")) {
int value = int.Parse(tppPowerSnapshot.Replace(" W", "").Trim());
if (value >= 20 && value <= 254) {
SetConcurrentTdp((byte)value);
if (tppTrackBar != null && tppTrackBar.Minimum <= value && value <= tppTrackBar.Maximum) {
tppTrackBar.Value = value;
}
UpdateCheckedState("tppPowerGroup", Strings.SetTppSlider);
}
}
});
}
//powerLimit4 = (string)key.GetValue("PL4Power", "null");
//if (powerLimit4 == "null") {
// UpdateCheckedState("pl4PowerGroup", "不设置");
//} else if (powerLimit4 == "max") {
// if (isTwoBytePL4) {
// SetPL4DoubleByte(500);
// } else {
// SetCpuPowerLimit4(254);
// }
// UpdateCheckedState("pl4PowerGroup", "最大");
//} else if (powerLimit4.Contains(" W")) {
// int value = int.Parse(powerLimit4.Replace(" W", "").Trim());
// int doubleFactor = isTwoBytePL4 ? 2 : 1;
// if (value >= 40 && value <= 240 * doubleFactor) {
// if (isTwoBytePL4) {
// SetPL4DoubleByte((ushort)value);
// } else {
// SetCpuPowerLimit4((byte)value);
// }
// UpdateCheckedState("pl4PowerGroup", powerLimit4);
// }
//}
iccMax = (string)key.GetValue("IccMax", "null");
if (iccMax == "null") {
UpdateCheckedState("iccMaxGroup", Strings.NotSet);
} else if (iccMax.Contains(" A")) {
if (int.TryParse(iccMax.Replace(" A", "").Trim(), out int ampVal) && ampVal >= 150 && ampVal <= 350) {
SetIccMaxByWmi((decimal)ampVal);
UpdateCheckedState("iccMaxGroup", iccMax);
}
}
acLoadline = (string)key.GetValue("AcLoadLine", "null");
if (acLoadline == "null") {
UpdateCheckedState("acLoadLineGroup", Strings.NotSet);
} else if (int.TryParse(acLoadline, out int llVal) && llVal >= 1) {
SetLoadLine(llVal);
string llDisplay = (180 - 10 * llVal).ToString();
UpdateCheckedState("acLoadLineGroup", llDisplay);
}
cpuPower = (string)key.GetValue("CpuPower", "null");
if (cpuPower == "null") {
UpdateCheckedState("cpuPowerGroup", Strings.NotSet);
} else if (cpuPower == "max") {
SetCpuPowerLimit(254);
if (cpuPowerTrackBar != null && 254 >= cpuPowerTrackBar.Minimum && 254 <= cpuPowerTrackBar.Maximum) {
cpuPowerTrackBar.Value = 254;
}
UpdateCheckedState("cpuPowerGroup", Strings.SetCpuPowerSlider);
} else if (cpuPower.Contains(" W")) {
int value = int.Parse(cpuPower.Replace(" W", "").Trim());
if (value >= 5 && value <= 254) {
SetCpuPowerLimit((byte)value);
if (cpuPowerTrackBar != null && value >= cpuPowerTrackBar.Minimum && value <= cpuPowerTrackBar.Maximum) {
cpuPowerTrackBar.Value = value;
}
UpdateCheckedState("cpuPowerGroup", Strings.SetCpuPowerSlider);
}
}
tgpPower = (string)key.GetValue("TgpPower", "on");
ppabPower = (string)key.GetValue("PpabPower", "on");
dState = (string)key.GetValue("DState", "normal");
SetGpuPowerState(tgpPower == "on", ppabPower == "on", dState == "normal" ? 1 : 2);
UpdateCheckedState("tgpPowerGroup", tgpPower == "on" ? Strings.Enable : Strings.Disable);
UpdateCheckedState("ppabPowerGroup", ppabPower == "on" ? Strings.Enable : Strings.Disable);
UpdateCheckedState("dStateGroup", dState == "normal" ? Strings.Normal : Strings.LowPower);
if (hasNVIDIAGpu) {
gpuClock = (int)key.GetValue("GpuClock", 0);
if (SetGPUClockLimit(gpuClock)) {
if (gpuClock > 0 && gpuClockTrackBar != null && gpuClockTrackBar.Minimum <= gpuClock / 10 && gpuClock / 10 <= gpuClockTrackBar.Maximum) {
gpuClockTrackBar.Value = gpuClock / 10;
UpdateCheckedState("gpuClockGroup", Strings.SetGpuClockSlider);
} else if (gpuClock == 0) {
UpdateCheckedState("gpuClockGroup", Strings.Restore);
}
} else {
UpdateCheckedState("gpuClockGroup", Strings.Restore);
}
DBVersion = (int)key.GetValue("DBVersion", 2);
switch (DBVersion) {
case 1:
string gpuModel = GetNVIDIAModel();
if (gpuModel != null) {
var match = Regex.Match(gpuModel, @"^\d+");
if (match.Success && int.TryParse(match.Value, out int modelNum)) {
if (modelNum >= 5000) {
DBVersion = 2;
string deviceId50 = "\"ACPI\\NVDA0820\\NPCF\"";
string command50 = $"pnputil /enable-device {deviceId50}";
ExecuteCommand(command50);
UpdateCheckedState("DBGroup", Strings.DbNormal);
break;
}
}
}
DBVersion = 1;
SetGpuPowerState(true, true); // fallback for db state
SetCpuPowerLimit((byte)CPULimitDB);
countDB = countDBInit;
DBMenu.Enabled = false;
UpdateCheckedState("DBGroup", Strings.DbUnlocked);
break;
case 2:
string deviceId = "\"ACPI\\NVDA0820\\NPCF\"";
string command = $"pnputil /enable-device {deviceId}";
ExecuteCommand(command);
DBVersion = 2;
UpdateCheckedState("DBGroup", Strings.DbNormal);
break;
}
}
autoStart = (string)key.GetValue("AutoStart", "off");
switch (autoStart) {
case "on":
AutoStartEnable();
UpdateCheckedState("autoStartGroup", Strings.Enable);
break;
case "off":
UpdateCheckedState("autoStartGroup", Strings.Disable);
break;
}
alreadyRead = (int)key.GetValue("AlreadyRead", 0);
customIcon = (string)key.GetValue("CustomIcon", "original");
switch (customIcon) {
case "original":
trayIcon.Icon = Properties.Resources.smallfan;
UpdateCheckedState("customIconGroup", Strings.IconOriginal);
break;
case "custom":
SetCustomIcon();
UpdateCheckedState("customIconGroup", Strings.IconCustom);
break;
case "dynamic":
UpdateDynamicIcon();
UpdateCheckedState("customIconGroup", Strings.IconDynamic);
break;
}
omenKey = (string)key.GetValue("OmenKey", "default");
switch (omenKey) {
case "default":
checkFloatingTimer.Enabled = false;
OmenKeyOff();
OmenKeyOn(omenKey);
UpdateCheckedState("omenKeyGroup", Strings.OmenKeyDefault);
break;
case "custom":
checkFloatingTimer.Enabled = true;
OmenKeyOff();
OmenKeyOn(omenKey);
UpdateCheckedState("omenKeyGroup", Strings.OmenKeyToggle);
break;
case "none":
checkFloatingTimer.Enabled = false;
OmenKeyOff();
UpdateCheckedState("omenKeyGroup", Strings.OmenKeyNone);
break;
}
bool monitorCPUCache = Convert.ToBoolean(key.GetValue("MonitorCPU", true));
monitorCPU = monitorCPUCache;
UpdateCheckedState("monitorCPUGroup", monitorCPU ? Strings.MonitorCpuOn : Strings.MonitorCpuOff);
if (hasNVIDIAGpu || hasAMDDiscreteGpu) {
bool monitorGPUCache = Convert.ToBoolean(key.GetValue("MonitorGPU", true));
monitorGPU = monitorGPUCache;
UpdateCheckedState("monitorGPUGroup", monitorGPU ? Strings.MonitorGpuOn : Strings.MonitorGpuOff);
} else {
monitorGPU = false;
UpdateCheckedState("monitorGPUGroup", monitorGPU ? Strings.MonitorGpuOn : Strings.MonitorGpuOff);
}
// 仅当至少一个监控开启时才启动 libre 进程;进程启动后再发送 CPU/GPU 状态
if (monitorCPU || monitorGPU) {
StartHardwareMonitor(); // 内部已调用 SetCpuMonitorState / SetGpuMonitorState
}
bool monitorFanCache = Convert.ToBoolean(key.GetValue("MonitorFan", false));
if (monitorFanCache == true) {
monitorFan = true;
UpdateCheckedState("monitorFanGroup", Strings.MonitorFanOn);
} else {
monitorFan = false;
UpdateCheckedState("monitorFanGroup", Strings.MonitorFanOff);
}
monitorRefreshRate = (string)key.GetValue("MonitorRefreshRate", "low");
switch (monitorRefreshRate) {
case "high":
tooltipUpdateTimer.Interval = 250;
SetMonitorInterval(250);
UpdateCheckedState("monitorRefreshGroup", Strings.MonitorRefreshHigh);
break;
case "low":
default:
monitorRefreshRate = "low";
tooltipUpdateTimer.Interval = 1000;
SetMonitorInterval(1000);
UpdateCheckedState("monitorRefreshGroup", Strings.MonitorRefreshLow);
break;
}
tempDisplayMode = (string)key.GetValue("TempDisplayMode", "smoothed");
if (tempDisplayMode == "raw") {
UpdateCheckedState("tempDisplayGroup", Strings.TempRaw);
} else {
tempDisplayMode = "smoothed";
UpdateCheckedState("tempDisplayGroup", Strings.TempSmoothed);
}
textSize = (int)key.GetValue("FloatingBarSize", 48);
UpdateFloatingText();
switch (textSize) {
case 24:
UpdateCheckedState("floatingBarSizeGroup", Strings.FontSize24);
break;
case 36:
UpdateCheckedState("floatingBarSizeGroup", Strings.FontSize36);
break;
case 48:
UpdateCheckedState("floatingBarSizeGroup", Strings.FontSize48);
break;
}
floatingBarLoc = (string)key.GetValue("FloatingBarLoc", "left");
UpdateFloatingText();
if (floatingBarLoc == "left") {
UpdateCheckedState("floatingBarLocGroup", Strings.FloatingLocLeft);
} else {
UpdateCheckedState("floatingBarLocGroup", Strings.FloatingLocRight);
}
floatingBar = (string)key.GetValue("FloatingBar", "off");
if (floatingBar == "on") {
ShowFloatingForm();
UpdateCheckedState("floatingBarGroup", Strings.FloatingShow);
} else {
CloseFloatingForm();
UpdateCheckedState("floatingBarGroup", Strings.FloatingHide);
}
dataLocalize = (string)key.GetValue("DataLocalize", "off");
if (dataLocalize == "on") {
UpdateCheckedState("dataLocalizeGroup", Strings.Enable);
} else {
UpdateCheckedState("dataLocalizeGroup", Strings.Disable);
}
// 恢复语言设置菜单勾选(语言本身已在 LoadLanguageSetting 中生效)
appLanguage = (string)key.GetValue("AppLanguage", "zh-CN");
RestoreLanguageChecked();
} else {
// 如果注册表键不存在,可以使用默认值
LoadFanConfig("cool.txt");
SetMaxFanSpeedOff();
SetGpuPowerState(true, true); // fallback for default state
// 首次运行:默认开启 CPU/GPU 监控,启动进程
StartHardwareMonitor();
}
}
} catch (Exception ex) {
Logger.Error($"Error restoring configuration: {ex.Message}");
}
// 保证应用启动时如果不包含 DataLocalize 键(第一次运行或旧版升级),菜单项UI依然能被初始化选中
if (dataLocalize == "on") {
UpdateCheckedState("dataLocalizeGroup", Strings.Enable);
} else {
UpdateCheckedState("dataLocalizeGroup", Strings.Disable);
}
}
}
}