-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathForm1.cs
More file actions
1421 lines (1251 loc) · 56.4 KB
/
Form1.cs
File metadata and controls
1421 lines (1251 loc) · 56.4 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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using WindowsHelloIRHelper.Services;
using WindowsHelloIRHelper.Interfaces;
namespace WindowsHelloIRHelper
{
public partial class Form1 : Form
{
private readonly IEventLogger _eventLogger;
private readonly SimpleCameraHelper _cameraHelper;
private readonly SimpleConfigHelper _configHelper;
private List<CameraDevice> _availableCameras = [];
private SimpleConfig? _currentConfig;
private readonly System.Windows.Forms.Timer _statusUpdateTimer;
private DateTime _lastEventLogCheck = DateTime.Now;
public Form1(IEventLogger eventLogger, SimpleCameraHelper cameraHelper, SimpleConfigHelper configHelper)
{
InitializeComponent();
_eventLogger = eventLogger;
_cameraHelper = cameraHelper;
_configHelper = configHelper;
// 初始化事件日志记录器
_ = InitializeEventLoggerAsync();
// 初始化状态更新定时器
_statusUpdateTimer = new System.Windows.Forms.Timer
{
Interval = 5000 // 每5秒更新一次状态
};
_statusUpdateTimer.Tick += StatusUpdateTimer_Tick;
_statusUpdateTimer.Start();
}
/// <summary>
/// 初始化事件日志记录器
/// </summary>
private async Task InitializeEventLoggerAsync()
{
try
{
await _eventLogger.InitializeAsync();
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"初始化事件日志记录器失败: {ex.Message}");
}
}
/// <summary>
/// 异步记录信息日志
/// </summary>
/// <param name="eventId">事件ID</param>
/// <param name="message">消息内容</param>
private async Task LogInformationAsync(int eventId, string message)
{
try
{
await _eventLogger.LogInformationAsync(eventId, message);
}
catch (Exception ex)
{
// 如果日志记录失败,输出到调试控制台
System.Diagnostics.Debug.WriteLine($"记录日志失败: {ex.Message}");
}
}
/// <summary>
/// 异步记录错误日志
/// </summary>
/// <param name="eventId">事件ID</param>
/// <param name="message">消息内容</param>
/// <param name="exception">异常信息(可选)</param>
private async Task LogErrorAsync(int eventId, string message, Exception? exception = null)
{
try
{
await _eventLogger.LogErrorAsync(eventId, message, exception);
}
catch (Exception ex)
{
// 如果日志记录失败,输出到调试控制台
System.Diagnostics.Debug.WriteLine($"记录日志失败: {ex.Message}");
}
}
/// <summary>
/// 同步记录信息日志(用于UI线程)
/// </summary>
/// <param name="eventId">事件ID</param>
/// <param name="message">消息内容</param>
private void LogInformation(int eventId, string message)
{
// 在UI线程中同步调用异步方法,避免死锁
Task.Run(async () => await LogInformationAsync(eventId, message));
}
/// <summary>
/// 同步记录错误日志(用于UI线程)
/// </summary>
/// <param name="eventId">事件ID</param>
/// <param name="message">消息内容</param>
/// <param name="exception">异常信息(可选)</param>
private void LogError(int eventId, string message, Exception? exception = null)
{
// 在UI线程中同步调用异步方法,避免死锁
Task.Run(async () => await LogErrorAsync(eventId, message, exception));
}
/// <summary>
/// 将状态消息追加到状态文本框,自动添加时间戳并滚动到最新消息
/// </summary>
/// <param name="message">要显示的消息</param>
private void AppendStatus(string message)
{
string timestampedMessage = $"[{DateTime.Now:HH:mm:ss}] {message}";
if (txtStatus.Text.Length > 0)
{
txtStatus.AppendText(Environment.NewLine);
}
txtStatus.AppendText(timestampedMessage);
// 自动滚动到最新消息
txtStatus.SelectionStart = txtStatus.Text.Length;
txtStatus.ScrollToCaret();
}
/// <summary>
/// 窗体加载事件,执行初始化检查
/// </summary>
private void Form1_Load(object? sender, EventArgs e)
{
// 首次加载时应用本地化文本(避免被设计器覆盖)
RefreshUILanguage();
// 显示欢迎消息
AppendStatus(Properties.Resources.UI_Form1_WelcomeMessage);
AppendStatus(Properties.Resources.UI_Form1_FunctionDescription);
AppendStatus(Properties.Resources.UI_Form1_Feature1);
AppendStatus(Properties.Resources.UI_Form1_Feature2);
AppendStatus("---");
// 初始化界面
_ = InitializeUIAsync();
// 检查光线传感器可用性
if (SimpleLightSensorHelper.IsAvailable())
{
AppendStatus(Properties.Resources.Status_LightSensorAvailable);
}
else
{
AppendStatus(Properties.Resources.Status_LightSensorNotDetected);
}
// 检查管理员权限
if (_cameraHelper.IsRunningAsAdministrator())
{
AppendStatus(Properties.Resources.Status_RunningAsAdmin);
}
else
{
AppendStatus(Properties.Resources.Status_NotRunningAsAdmin);
AppendStatus(Properties.Resources.Status_AdminRequiredHint);
LogError(EventIds.InsufficientPermissions, "用户界面未以管理员权限运行");
}
AppendStatus("---");
AppendStatus(Properties.Resources.Status_Ready);
}
/// <summary>
/// 检测光亮度按钮点击事件处理
/// </summary>
private void btnDetectLight_Click(object? sender, EventArgs e)
{
try
{
// 禁用按钮防止重复操作
btnDetectLight.Enabled = false;
AppendStatus(Properties.Resources.Status_DetectingLight);
// 调用简化的光线传感器工具获取光亮度
var lux = SimpleLightSensorHelper.GetCurrentLux();
// 显示结果
if (lux.HasValue)
{
lblDetectLight.Text = $"{lux.Value:F2} lux";
AppendStatus(string.Format(Properties.Resources.Status_LightValue, lux.Value));
LogInformation(EventIds.LightSensorEnabled, $"用户检测光亮度: {lux.Value:F2} lux");
}
else
{
AppendStatus(Properties.Resources.Status_ErrorCannotGetLight);
}
}
catch (Exception ex)
{
AppendStatus(string.Format(Properties.Resources.Status_Exception, ex.Message));
LogError(EventIds.SensorUnavailable, "检测光亮度异常", ex);
}
finally
{
// 重新启用按钮
btnDetectLight.Enabled = true;
}
}
/// <summary>
/// 启用/禁用摄像头按钮点击事件处理
/// </summary>
private async void btnToggleCamera_Click(object? sender, EventArgs e)
{
try
{
// 检查是否选择了摄像头
if (cmbCameraList.SelectedIndex < 0 ||
cmbCameraList.SelectedIndex >= _availableCameras.Count)
{
AppendStatus(Properties.Resources.Status_ErrorSelectCamera);
return;
}
// 检查管理员权限
if (!_cameraHelper.IsRunningAsAdministrator())
{
AppendStatus(Properties.Resources.Status_ErrorAdminRequired);
AppendStatus(Properties.Resources.Status_RunAsAdmin);
return;
}
// 禁用按钮防止重复操作
btnToggleCamera.Enabled = false;
var selectedCamera = _availableCameras[cmbCameraList.SelectedIndex];
AppendStatus(string.Format(Properties.Resources.Status_TogglingCamera, selectedCamera.Name));
// 简化版本:直接执行相反操作(假设当前状态与按钮文本相反)
bool enable = btnToggleCamera.Text == Properties.Resources.UI_Button_EnableCamera;
bool success;
if (enable)
{
success = await _cameraHelper.EnableCameraAsync(selectedCamera.DeviceId);
}
else
{
success = await _cameraHelper.DisableCameraAsync(selectedCamera.DeviceId);
// 如果禁用摄像头,同时停止视频预览
if (success && _isVideoInitialized)
{
await StopVideoPreviewAsync();
btnPreview.Text = Properties.Resources.UI_Button_StartPreview;
AppendStatus(Properties.Resources.Status_CameraDisabledPreviewStopped);
}
}
// 显示操作结果
if (success)
{
string stateText = enable ? Properties.Resources.Status_CameraEnabled : Properties.Resources.Status_CameraDisabled;
AppendStatus(string.Format(Properties.Resources.Status_CameraStateChanged, selectedCamera.Name, stateText));
// 更新状态显示
await UpdateCameraStatusAsync();
// 记录用户操作
LogInformation(enable ? EventIds.CameraEnabled : EventIds.CameraDisabled,
$"用户通过界面{stateText}摄像头: {selectedCamera.Name}");
}
else
{
AppendStatus(Properties.Resources.Status_OperationFailed);
}
}
catch (Exception ex)
{
AppendStatus(string.Format(Properties.Resources.Status_Exception, ex.Message));
LogError(EventIds.CameraControlFailed, "摄像头控制操作异常", ex);
}
finally
{
// 重新启用按钮
btnToggleCamera.Enabled = true;
}
}
/// <summary>
/// 异步初始化用户界面
/// </summary>
private async Task InitializeUIAsync()
{
try
{
// 加载配置
_currentConfig = _configHelper.LoadConfig();
// 初始化界面控件
await LoadCameraListAsync();
UpdateConfigUI();
UpdateServiceStatusUI();
}
catch (Exception ex)
{
AppendStatus(string.Format(Properties.Resources.Status_InitUIFailed, ex.Message));
LogError(EventIds.ServiceException, "初始化界面失败", ex);
}
}
/// <summary>
/// 异步加载摄像头设备列表
/// </summary>
private async Task LoadCameraListAsync()
{
try
{
AppendStatus(Properties.Resources.Status_EnumeratingCameras);
// 使用简化的摄像头工具枚举摄像头
_availableCameras = await _cameraHelper.GetAvailableCamerasAsync();
AppendStatus(string.Format(Properties.Resources.Status_EnumerationComplete, _availableCameras.Count));
// 更新下拉列表
cmbCameraList.Items.Clear();
if (_availableCameras.Count == 0)
{
cmbCameraList.Items.Add(Properties.Resources.UI_CameraList_NoCameraFound);
cmbCameraList.SelectedIndex = 0;
cmbCameraList.Enabled = false;
btnToggleCamera.Enabled = false;
lblCameraStatus.Text = Properties.Resources.Status_CameraStatusNoDevice;
AppendStatus(Properties.Resources.Status_NoCamerasFound);
AppendStatus(Properties.Resources.Status_PossibleReasons);
AppendStatus(Properties.Resources.Status_Reason1);
AppendStatus(Properties.Resources.Status_Reason2);
}
else
{
AppendStatus(Properties.Resources.Status_DeviceList);
foreach (var camera in _availableCameras)
{
cmbCameraList.Items.Add(camera.Name);
string stateText = camera.IsEnabled switch
{
true => Properties.Resources.Status_CameraEnabled,
false => Properties.Resources.Status_CameraDisabled
};
AppendStatus(string.Format(Properties.Resources.Status_DeviceItem, camera.Name, stateText));
}
// 选择配置中指定的摄像头或第一个摄像头
int selectedIndex = 0;
if (_currentConfig != null && !string.IsNullOrEmpty(_currentConfig.TargetCameraDeviceId))
{
var configuredCamera = _availableCameras.FindIndex(c =>
c.DeviceId == _currentConfig.TargetCameraDeviceId);
if (configuredCamera >= 0)
{
selectedIndex = configuredCamera;
AppendStatus(string.Format(Properties.Resources.Status_SelectedConfiguredCamera, _availableCameras[selectedIndex].Name));
}
}
else
{
// 优先选择第一个摄像头
if (_availableCameras.Count >= 0)
{
selectedIndex = 0;
AppendStatus(string.Format(Properties.Resources.Status_SelectedIntegratedCamera, _availableCameras[selectedIndex].Name));
}
}
cmbCameraList.SelectedIndex = selectedIndex;
cmbCameraList.Enabled = true;
btnToggleCamera.Enabled = true;
AppendStatus(Properties.Resources.Status_CameraListLoaded);
await UpdateCameraStatusAsync();
}
}
catch (Exception ex)
{
AppendStatus(string.Format(Properties.Resources.Status_LoadCameraListFailed, ex.Message));
AppendStatus(string.Format(Properties.Resources.Status_ExceptionType, ex.GetType().Name));
if (ex.InnerException != null)
{
AppendStatus(string.Format(Properties.Resources.Status_InnerException, ex.InnerException.Message));
}
AppendStatus(string.Format(Properties.Resources.Status_StackTrace, ex.StackTrace));
LogError(EventIds.MonitorStartFailed, "加载摄像头列表失败", ex);
cmbCameraList.Items.Clear();
cmbCameraList.Items.Add(Properties.Resources.UI_CameraList_LoadFailed);
cmbCameraList.SelectedIndex = 0;
cmbCameraList.Enabled = false;
btnToggleCamera.Enabled = false;
lblCameraStatus.Text = Properties.Resources.Status_CameraStatusLoadFailed;
}
}
/// <summary>
/// 异步更新摄像头状态显示
/// </summary>
private async Task UpdateCameraStatusAsync()
{
try
{
if (cmbCameraList.SelectedIndex < 0 ||
cmbCameraList.SelectedIndex >= _availableCameras.Count)
{
lblCameraStatus.Text = Properties.Resources.Status_CameraStatusNotSelected;
return;
}
var selectedCamera = _availableCameras[cmbCameraList.SelectedIndex];
// 实时查询摄像头状态,而不是使用缓存的状态
var currentState = await _cameraHelper.GetDeviceEnabledAsync(selectedCamera.DeviceId);
string stateText = currentState switch
{
true => Properties.Resources.Status_CameraEnabled,
false => Properties.Resources.Status_CameraDisabled
};
lblCameraStatus.Text = string.Format(Properties.Resources.Status_CameraStatusLabel, stateText);
// 更新按钮文本
btnToggleCamera.Text = currentState ? Properties.Resources.UI_Button_DisableCamera : Properties.Resources.UI_Button_EnableCamera;
}
catch (Exception ex)
{
lblCameraStatus.Text = Properties.Resources.Status_CameraStatusQueryFailed;
AppendStatus(string.Format(Properties.Resources.Status_QueryCameraStatusFailed, ex.Message));
}
}
/// <summary>
/// 更新配置界面显示
/// </summary>
private void UpdateConfigUI()
{
try
{
// 更新环境光传感器启用状态
if (_currentConfig != null)
{
chkEnableLightSensor.Checked = _currentConfig.EnableLightSensor;
// 更新参数配置 - 简化版本只有光亮度阈值
// 确保值在控件的有效范围内
decimal thresholdValue = (decimal)_currentConfig.LightThreshold;
if (thresholdValue < numThreshold.Minimum)
thresholdValue = numThreshold.Minimum;
else if (thresholdValue > numThreshold.Maximum)
thresholdValue = numThreshold.Maximum;
numThreshold.Value = thresholdValue;
// 根据环境光传感器启用状态启用/禁用相关控件
numThreshold.Enabled = _currentConfig.EnableLightSensor;
lblThreshold.Enabled = _currentConfig.EnableLightSensor;
}
}
catch (Exception ex)
{
AppendStatus(string.Format(Properties.Resources.Status_UpdateConfigUIFailed, ex.Message));
}
}
/// <summary>
/// 更新服务状态界面显示
/// </summary>
private void UpdateServiceStatusUI()
{
try
{
var serviceStatus = ServiceManager.GetDetailedServiceStatus();
string statusText = Properties.Resources.Status_ServiceNotInstalled;
if (serviceStatus.IsInstalled)
{
statusText = serviceStatus.Status switch
{
ServiceControllerStatus.Running => Properties.Resources.Status_ServiceRunning,
ServiceControllerStatus.Stopped => Properties.Resources.Status_ServiceStopped_State,
ServiceControllerStatus.StartPending => Properties.Resources.Status_ServiceStartPending,
ServiceControllerStatus.StopPending => Properties.Resources.Status_ServiceStopPending,
ServiceControllerStatus.Paused => Properties.Resources.Status_ServicePaused,
_ => Properties.Resources.Status_ServiceUnknown
};
}
lblServiceStatus.Text = string.Format(Properties.Resources.Status_ServiceStatusLabel, statusText);
// 更新按钮状态
btnInstallService.Enabled = !serviceStatus.IsInstalled && serviceStatus.HasAdminRights;
btnUninstallService.Enabled = serviceStatus.IsInstalled && serviceStatus.HasAdminRights;
btnStartService.Enabled = serviceStatus.CanStart && serviceStatus.HasAdminRights;
btnStopService.Enabled = serviceStatus.CanStop && serviceStatus.HasAdminRights;
if (!serviceStatus.HasAdminRights)
{
lblServiceStatus.Text += Properties.Resources.Status_ServiceAdminRequired;
}
}
catch (Exception ex)
{
lblServiceStatus.Text = Properties.Resources.Status_ServiceStatusQueryFailed;
AppendStatus(string.Format(Properties.Resources.Status_QueryServiceStatusFailed, ex.Message));
}
}
/// <summary>
/// 摄像头选择变化事件处理
/// </summary>
private async void cmbCameraList_SelectedIndexChanged(object? sender, EventArgs e)
{
await UpdateCameraStatusAsync();
// 当切换摄像头时,如果正在预览,则停止预览
if (_isVideoInitialized)
{
await StopVideoPreviewAsync();
btnPreview.Text = Properties.Resources.UI_Button_StartPreview;
}
}
/// <summary>
/// 刷新摄像头列表按钮点击事件处理
/// </summary>
private async void btnRefreshCameras_Click(object? sender, EventArgs e)
{
try
{
btnRefreshCameras.Enabled = false;
AppendStatus(Properties.Resources.Status_RefreshingCameraList);
await LoadCameraListAsync();
AppendStatus(Properties.Resources.Status_CameraListRefreshed);
}
catch (Exception ex)
{
AppendStatus(string.Format(Properties.Resources.Status_Exception, ex.Message));
LogError(EventIds.MonitorStartFailed, "刷新摄像头列表失败", ex);
}
finally
{
btnRefreshCameras.Enabled = true;
}
}
/// <summary>
/// 环境光传感器启用状态变化事件处理
/// </summary>
private void chkEnableLightSensor_CheckedChanged(object? sender, EventArgs e)
{
// 根据环境光传感器启用状态启用/禁用相关控件
bool enabled = chkEnableLightSensor.Checked;
numThreshold.Enabled = enabled;
lblThreshold.Enabled = enabled;
string state = enabled ? Properties.Resources.Status_Enabled : Properties.Resources.Status_Disabled;
AppendStatus(string.Format(Properties.Resources.Status_LightSensorStateChanged, state));
}
/// <summary>
/// 清空状态日志按钮点击事件处理
/// </summary>
private void btnClearStatus_Click(object? sender, EventArgs e)
{
txtStatus.Clear();
AppendStatus(Properties.Resources.Status_LogCleared);
}
/// <summary>
/// 保存配置按钮点击事件处理
/// </summary>
private async void btnSaveConfig_Click(object? sender, EventArgs e)
{
try
{
btnSaveConfig.Enabled = false;
AppendStatus(Properties.Resources.Status_SavingConfig);
// 创建新的简化配置对象
var newConfig = new SimpleConfig
{
// 更新环境光传感器启用状态
EnableLightSensor = chkEnableLightSensor.Checked,
// 更新环境光传感器配置 - 简化版本只有光亮度阈值
LightThreshold = (double)numThreshold.Value,
// 更新目标摄像头设备ID
TargetCameraDeviceId = (cmbCameraList.SelectedIndex >= 0 &&
cmbCameraList.SelectedIndex < _availableCameras.Count)
? _availableCameras[cmbCameraList.SelectedIndex].DeviceId
: null
};
// 使用 SimpleConfigHelper 保存配置
await _configHelper.SaveConfigAsync(newConfig);
_currentConfig = newConfig;
AppendStatus(Properties.Resources.Status_ConfigSaved);
LogInformation(EventIds.ConfigReloaded, Properties.Resources.Log_Config_SavedByUser);
}
catch (Exception ex)
{
AppendStatus(string.Format(Properties.Resources.Status_Exception, ex.Message));
LogError(EventIds.ConfigLoadFailed, Properties.Resources.Log_Config_SaveFailed, ex);
}
finally
{
btnSaveConfig.Enabled = true;
}
}
/// <summary>
/// 重置配置按钮点击事件处理
/// </summary>
private async void btnResetConfig_Click(object? sender, EventArgs e)
{
try
{
var result = MessageBox.Show(
Properties.Resources.Message_ConfirmResetConfig,
Properties.Resources.Message_ConfirmResetConfigTitle,
MessageBoxButtons.YesNo,
MessageBoxIcon.Question);
if (result != DialogResult.Yes)
{
return;
}
btnResetConfig.Enabled = false;
AppendStatus(Properties.Resources.Status_ResettingConfig);
// 创建默认简化配置
var defaultConfig = new SimpleConfig
{
TargetCameraDeviceId = (cmbCameraList.SelectedIndex >= 0 &&
cmbCameraList.SelectedIndex < _availableCameras.Count)
? _availableCameras[cmbCameraList.SelectedIndex].DeviceId
: null,
EnableLightSensor = false,
LightThreshold = 10.0
};
// 使用 SimpleConfigHelper 保存默认配置
await _configHelper.SaveConfigAsync(defaultConfig);
_currentConfig = defaultConfig;
// 更新界面显示
UpdateConfigUI();
AppendStatus(Properties.Resources.Status_ConfigReset);
LogInformation(EventIds.ConfigReloaded, Properties.Resources.Log_Config_ResetByUser);
}
catch (Exception ex)
{
AppendStatus(string.Format(Properties.Resources.Status_Exception, ex.Message));
LogError(EventIds.ConfigLoadFailed, Properties.Resources.Log_Config_ResetFailed, ex);
}
finally
{
btnResetConfig.Enabled = true;
}
}
/// <summary>
/// 导出配置到文件
/// </summary>
private async void ExportConfig()
{
try
{
using var saveDialog = new SaveFileDialog
{
Title = Properties.Resources.Dialog_ExportConfig_Title,
Filter = Properties.Resources.Dialog_ExportConfig_Filter,
DefaultExt = "json",
FileName = $"AutoCameraControl_Config_{DateTime.Now:yyyyMMdd_HHmmss}.json"
};
if (saveDialog.ShowDialog() == DialogResult.OK)
{
AppendStatus(Properties.Resources.Status_ExportingConfig);
var configJson = System.Text.Json.JsonSerializer.Serialize(_currentConfig ?? new SimpleConfig(), new System.Text.Json.JsonSerializerOptions
{
WriteIndented = true,
PropertyNamingPolicy = System.Text.Json.JsonNamingPolicy.CamelCase
});
await System.IO.File.WriteAllTextAsync(saveDialog.FileName, configJson);
AppendStatus(string.Format(Properties.Resources.Status_ConfigExported, saveDialog.FileName));
LogInformation(EventIds.ConfigReloaded, string.Format(Properties.Resources.Log_Config_ExportedByUser, saveDialog.FileName));
}
}
catch (Exception ex)
{
AppendStatus(string.Format(Properties.Resources.Status_ExportConfigFailed, ex.Message));
LogError(EventIds.ConfigLoadFailed, Properties.Resources.Log_Config_ExportFailed, ex);
}
}
/// <summary>
/// 从文件导入配置
/// </summary>
private async void ImportConfig()
{
try
{
using var openDialog = new OpenFileDialog
{
Title = Properties.Resources.Dialog_ImportConfig_Title,
Filter = Properties.Resources.Dialog_ImportConfig_Filter,
DefaultExt = "json"
};
if (openDialog.ShowDialog() == DialogResult.OK)
{
AppendStatus(Properties.Resources.Status_ImportingConfig);
var configJson = await System.IO.File.ReadAllTextAsync(openDialog.FileName);
var importedConfig = System.Text.Json.JsonSerializer.Deserialize<SimpleConfig>(configJson, new System.Text.Json.JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
if (importedConfig == null)
{
AppendStatus(Properties.Resources.Status_ImportFailed_InvalidFormat);
return;
}
// 使用 SimpleConfigHelper 保存导入的配置
await _configHelper.SaveConfigAsync(importedConfig);
_currentConfig = importedConfig;
// 更新界面显示
UpdateConfigUI();
AppendStatus(string.Format(Properties.Resources.Status_ConfigImported, openDialog.FileName));
LogInformation(EventIds.ConfigReloaded, string.Format(Properties.Resources.Log_Config_ImportedByUser, openDialog.FileName));
}
}
catch (Exception ex)
{
AppendStatus(string.Format(Properties.Resources.Status_ImportConfigFailed, ex.Message));
LogError(EventIds.ConfigLoadFailed, Properties.Resources.Log_Config_ImportFailed, ex);
}
}
/// <summary>
/// 注册服务按钮点击事件处理
/// </summary>
private async void btnInstallService_Click(object? sender, EventArgs e)
{
try
{
btnInstallService.Enabled = false;
AppendStatus(Properties.Resources.Status_InstallingService);
// 使用 AdvancedServiceInstaller 进行服务安装
var exePath = Application.ExecutablePath;
var installResult = await AdvancedServiceInstaller.InstallServiceWithScAsync(exePath);
if (installResult.Success)
{
AppendStatus(Properties.Resources.Status_ServiceInstalled);
AppendStatus(installResult.Message);
LogInformation(EventIds.ServiceStarted, "用户通过界面注册Windows服务");
}
else
{
AppendStatus(string.Format(Properties.Resources.Status_ServiceInstallFailed, installResult.Message));
if (!string.IsNullOrEmpty(installResult.ErrorDetails))
{
AppendStatus(string.Format(Properties.Resources.Status_Details, installResult.ErrorDetails));
}
}
// 更新服务状态显示
UpdateServiceStatusUI();
}
catch (Exception ex)
{
AppendStatus(string.Format(Properties.Resources.Status_Exception, ex.Message));
LogError(EventIds.ServiceException, "注册服务异常", ex);
}
finally
{
btnInstallService.Enabled = true;
}
}
/// <summary>
/// 卸载服务按钮点击事件处理
/// </summary>
private async void btnUninstallService_Click(object? sender, EventArgs e)
{
try
{
var result = MessageBox.Show(
Properties.Resources.Message_ConfirmUninstallService,
Properties.Resources.Message_ConfirmUninstallServiceTitle,
MessageBoxButtons.YesNo,
MessageBoxIcon.Question);
if (result != DialogResult.Yes)
{
return;
}
btnUninstallService.Enabled = false;
AppendStatus(Properties.Resources.Status_UninstallingService);
// 使用 AdvancedServiceInstaller 进行服务卸载
var uninstallResult = await AdvancedServiceInstaller.UninstallServiceWithScAsync();
if (uninstallResult.Success)
{
AppendStatus(Properties.Resources.Status_ServiceUninstalled);
AppendStatus(uninstallResult.Message);
LogInformation(EventIds.ServiceStopped, "用户通过界面卸载Windows服务");
}
else
{
AppendStatus(string.Format(Properties.Resources.Status_ServiceUninstallFailed, uninstallResult.Message));
if (!string.IsNullOrEmpty(uninstallResult.ErrorDetails))
{
AppendStatus(string.Format(Properties.Resources.Status_Details, uninstallResult.ErrorDetails));
}
}
// 更新服务状态显示
UpdateServiceStatusUI();
}
catch (Exception ex)
{
AppendStatus(string.Format(Properties.Resources.Status_Exception, ex.Message));
LogError(EventIds.ServiceException, "卸载服务异常", ex);
}
finally
{
btnUninstallService.Enabled = true;
}
}
/// <summary>
/// 启动服务按钮点击事件处理
/// </summary>
private void btnStartService_Click(object? sender, EventArgs e)
{
try
{
// 创建新的简化配置对象
var newConfig = new SimpleConfig
{
// 更新环境光传感器启用状态
EnableLightSensor = chkEnableLightSensor.Checked,
// 更新环境光传感器配置 - 简化版本只有光亮度阈值
LightThreshold = (double)numThreshold.Value,
// 更新目标摄像头设备ID
TargetCameraDeviceId = (cmbCameraList.SelectedIndex >= 0 &&
cmbCameraList.SelectedIndex < _availableCameras.Count)
? _availableCameras[cmbCameraList.SelectedIndex].DeviceId
: null
};
// 使用 SimpleConfigHelper 保存配置
_ = _configHelper.SaveConfigAsync(newConfig);
_currentConfig = newConfig;
AppendStatus(Properties.Resources.Status_ConfigSaved);
btnStartService.Enabled = false;
AppendStatus(Properties.Resources.Status_StartingService);
var startInfo = new ProcessStartInfo
{
FileName = "sc.exe",
Arguments = $"start \"{SimpleAutoCameraControlService.ServiceName}\"",
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
};
using var process = Process.Start(startInfo);
process?.WaitForExit();
if (process?.ExitCode == 0)
{
AppendStatus(Properties.Resources.Status_ServiceStarted);
LogInformation(EventIds.ServiceStarted, "用户通过界面启动Windows服务");
}
else
{
AppendStatus(Properties.Resources.Status_ServiceStartFailed);
}
// 更新服务状态显示
UpdateServiceStatusUI();
}
catch (Exception ex)
{
AppendStatus(string.Format(Properties.Resources.Status_Exception, ex.Message));
LogError(EventIds.ServiceException, "启动服务异常", ex);
}
finally
{
btnStartService.Enabled = true;
}
}
/// <summary>
/// 停止服务按钮点击事件处理
/// </summary>
private void btnStopService_Click(object? sender, EventArgs e)
{
try
{
btnStopService.Enabled = false;
AppendStatus(Properties.Resources.Status_StoppingService);
var startInfo = new ProcessStartInfo
{
FileName = "sc.exe",
Arguments = $"stop \"{SimpleAutoCameraControlService.ServiceName}\"",
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
};
using var process = Process.Start(startInfo);
process?.WaitForExit();
if (process?.ExitCode == 0)
{
AppendStatus(Properties.Resources.Status_ServiceStopped);
LogInformation(EventIds.ServiceStopped, "用户通过界面停止Windows服务");
}
else
{
AppendStatus(Properties.Resources.Status_ServiceStopFailed);
}
// 更新服务状态显示
UpdateServiceStatusUI();
}
catch (Exception ex)
{
AppendStatus(string.Format(Properties.Resources.Status_Exception, ex.Message));
LogError(EventIds.ServiceException, "停止服务异常", ex);
}
finally
{
btnStopService.Enabled = true;
}
}
/// <summary>
/// 定期更新服务状态显示
/// </summary>
private async void RefreshServiceStatus()
{
try
{
UpdateServiceStatusUI();
// 如果服务正在启动或停止中,继续监控状态变化
var serviceStatus = ServiceManager.GetDetailedServiceStatus();
if (serviceStatus.IsInstalled && serviceStatus.Status.HasValue)
{
var status = serviceStatus.Status.Value;
if (status == ServiceControllerStatus.StartPending ||
status == ServiceControllerStatus.StopPending)
{