-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKeyboardMonitor.cs
More file actions
1356 lines (1190 loc) · 51.4 KB
/
Copy pathKeyboardMonitor.cs
File metadata and controls
1356 lines (1190 loc) · 51.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.Drawing;
using System.Drawing.Drawing2D;
using System.Globalization;
using System.Linq;
using System.ComponentModel;
using System.Windows.Forms;
namespace KeyboardDiagnostic
{
public class KeyboardMonitorForm : Form
{
// 三種不同的鍵盤佈局定義
private static readonly string[][] MAIN_LAYOUT = new string[][]
{
new string[] { "ESC", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12" },
new string[] { "`", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "-", "=", "BACKSPACE" },
new string[] { "TAB", "Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "[", "]", "\\" },
new string[] { "CAPSLOCK", "A", "S", "D", "F", "G", "H", "J", "K", "L", ";", "'", "ENTER" },
new string[] { "SHIFT_L", "Z", "X", "C", "V", "B", "N", "M", ",", ".", "/", "SHIFT_R" },
new string[] { "CTRL_L", "WIN", "ALT_L", "SPACE", "ALT_R", "MENU", "CTRL_R" }
};
private static readonly string[][] NAV_LAYOUT = new string[][]
{
new string[] { "PRTSC", "SCROLL", "PAUSE" },
new string[] { "INSERT", "HOME", "PGUP" },
new string[] { "DELETE", "END", "PGDN" },
new string[] { "", "", "" },
new string[] { "", "↑", "" },
new string[] { "←", "↓", "→" }
};
private static readonly string[][] NUM_LAYOUT = new string[][]
{
new string[] { "", "", "", "" },
new string[] { "NUMLOCK", "NUM_/", "NUM_*", "NUM_-" },
new string[] { "NUM_7", "NUM_8", "NUM_9", "NUM_+" },
new string[] { "NUM_4", "NUM_5", "NUM_6", "" }, // NUM_+ 佔用
new string[] { "NUM_1", "NUM_2", "NUM_3", "NUM_ENTER" },
new string[] { "NUM_0", "", "NUM_.", "" } // NUM_0 與 NUM_ENTER 佔用
};
private readonly GlobalInputHook _inputHook = new GlobalInputHook();
private readonly KeyStateTracker _keyStateTracker = new KeyStateTracker();
private readonly TypingMetrics _typingMetrics = new TypingMetrics();
// UI 元件字典
private readonly Dictionary<string, KeyControl> _keyControls = new Dictionary<string, KeyControl>();
// 頂部狀態面板元件與佈局容器
private Label _statusLight;
private Label _statusText;
private Label _countLabel;
private Label _bottomTips;
private ComboBox _keyboardTypeSelector;
private TableLayoutPanel _keyboardContainer;
private Timer _watchdogTimer;
// --- 優化新增的 UI 元件 ---
private TableLayoutPanel _bottomPanelContainer;
private MouseTesterControl _mouseTester;
private TextBox _typeTextBox;
private Label _wpmLabel;
private Label _kpsLabel;
private Label _maxKpsLabel;
private Label _latencyLabel;
private ListBox _logListBox;
// 打字速度與按鍵計數統計
private readonly KeyRateCounter _keyRateCounter = new KeyRateCounter();
private double _lastLatencyMs;
private Timer _kpsTimer;
// --- 快取供高頻重繪使用的固定 GDI 資源(表單生命週期內重複使用,於 Dispose 釋放)---
private readonly Font _indicatorNameFont = new Font("Segoe UI", 8.5f, FontStyle.Regular);
private readonly Font _indicatorValueFont = new Font("Segoe UI", 13f, FontStyle.Bold);
private readonly Pen _indicatorBorderPen = new Pen(Color.FromArgb(40, 40, 48), 1f);
private readonly Pen _panelBorderPen = new Pen(Color.FromArgb(45, 45, 52), 1f);
private readonly SolidBrush _statusNormalBrush = new SolidBrush(Color.FromArgb(0x10, 0xB9, 0x81));
private readonly SolidBrush _statusStuckBrush = new SolidBrush(Color.FromArgb(0xEF, 0x44, 0x44));
private readonly SolidBrush _logDefaultBrush = new SolidBrush(Color.FromArgb(180, 180, 190));
private readonly SolidBrush _logPressBrush = new SolidBrush(Color.FromArgb(0, 242, 254));
private readonly SolidBrush _logReleaseBrush = new SolidBrush(Color.FromArgb(16, 185, 129));
private readonly SolidBrush _logStuckBrush = new SolidBrush(Color.FromArgb(239, 68, 68));
private readonly SolidBrush _logMouseBrush = new SolidBrush(Color.FromArgb(245, 158, 11));
[STAThread]
public static void Main()
{
Application.SetHighDpiMode(HighDpiMode.PerMonitorV2);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
using (var form = new KeyboardMonitorForm())
{
Application.Run(form);
}
}
public KeyboardMonitorForm()
{
InitializeComponent();
}
private void InitializeComponent()
{
this.DoubleBuffered = true;
// 設定視窗基本樣式
this.Text = "Windows 11 鍵盤與滑鼠診斷工具";
this.Width = 1450;
this.Height = 810;
this.StartPosition = FormStartPosition.CenterScreen;
this.FormBorderStyle = FormBorderStyle.FixedSingle;
this.MaximizeBox = false;
this.BackColor = Color.FromArgb(18, 18, 22);
// 1. 頂部控制面板
Panel topPanel = new Panel
{
Dock = DockStyle.Top,
Height = 65,
BackColor = Color.FromArgb(18, 18, 22),
Padding = new Padding(25, 10, 25, 10)
};
Label titleLabel = new Label
{
Text = "KEYBOARD & MOUSE DIAGNOSTIC",
Font = new Font("Segoe UI", 16, FontStyle.Bold),
ForeColor = Color.FromArgb(245, 245, 250),
AutoSize = true,
Location = new Point(25, 18)
};
topPanel.Controls.Add(titleLabel);
// 狀態列容器
FlowLayoutPanel statusPanel = new FlowLayoutPanel
{
FlowDirection = FlowDirection.LeftToRight,
WrapContents = false,
AutoSize = true,
BackColor = Color.Transparent,
Dock = DockStyle.Right,
Padding = new Padding(0, 15, 0, 0)
};
_statusLight = new Label
{
Width = 14,
Height = 14,
BackColor = _statusNormalBrush.Color, // 精緻綠
Margin = new Padding(5, 6, 5, 0)
};
// 繪製圓形指示燈(依目前狀態選用快取好的固定筆刷,避免每次重繪配置新物件)
_statusLight.Paint += (s, e) =>
{
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
SolidBrush b = _statusLight.BackColor == _statusStuckBrush.Color ? _statusStuckBrush : _statusNormalBrush;
e.Graphics.FillEllipse(b, 0, 0, _statusLight.Width - 1, _statusLight.Height - 1);
};
statusPanel.Controls.Add(_statusLight);
_statusText = new Label
{
Text = "系統偵測中 - 正常",
Font = new Font("Segoe UI", 10, FontStyle.Bold),
ForeColor = _statusNormalBrush.Color,
AutoSize = true,
Margin = new Padding(5, 4, 15, 0)
};
statusPanel.Controls.Add(_statusText);
_countLabel = new Label
{
Text = "當前按下鍵數: 0",
Font = new Font("Segoe UI", 10, FontStyle.Bold),
ForeColor = Color.FromArgb(245, 245, 250),
AutoSize = true,
Margin = new Padding(5, 4, 15, 0)
};
statusPanel.Controls.Add(_countLabel);
// 鍵盤種類下拉選單
_keyboardTypeSelector = new ComboBox
{
DropDownStyle = ComboBoxStyle.DropDownList,
Font = new Font("Segoe UI", 9.5f, FontStyle.Bold),
BackColor = Color.FromArgb(38, 38, 44),
ForeColor = Color.White,
FlatStyle = FlatStyle.Flat,
Size = new Size(160, 28),
Margin = new Padding(5, 1, 15, 0),
Cursor = Cursors.Hand,
TabStop = false,
AccessibleName = "鍵盤配置"
};
_keyboardTypeSelector.Items.AddRange(new object[] { "100% 全尺寸鍵盤", "80% TKL 鍵盤", "60% 緊湊型鍵盤" });
_keyboardTypeSelector.SelectedIndex = 0;
_keyboardTypeSelector.SelectedIndexChanged += KeyboardTypeSelector_SelectedIndexChanged;
statusPanel.Controls.Add(_keyboardTypeSelector);
// 清除按鈕
Button resetBtn = new Button
{
Text = "清除重設",
Font = new Font("Segoe UI", 9.5f, FontStyle.Bold),
BackColor = Color.FromArgb(59, 130, 246),
ForeColor = Color.White,
FlatStyle = FlatStyle.Flat,
Size = new Size(85, 28),
Margin = new Padding(5, 0, 5, 0),
Cursor = Cursors.Hand,
TabStop = false
};
resetBtn.FlatAppearance.BorderSize = 0;
resetBtn.FlatAppearance.MouseOverBackColor = Color.FromArgb(37, 99, 235);
resetBtn.Click += (s, e) => ResetAll();
statusPanel.Controls.Add(resetBtn);
topPanel.Controls.Add(statusPanel);
this.Controls.Add(topPanel);
// 2. 鍵盤主體卡片面板容器
_keyboardContainer = new TableLayoutPanel
{
BackColor = Color.FromArgb(24, 24, 28),
Padding = new Padding(15),
Location = new Point(25, 75),
Size = new Size(1385, 380),
RowCount = 1,
ColumnCount = 3
};
// 繪製容器邊框(使用快取的固定 Pen)
_keyboardContainer.Paint += (s, e) =>
{
e.Graphics.DrawRectangle(_panelBorderPen, 0, 0, _keyboardContainer.Width - 1, _keyboardContainer.Height - 1);
};
this.Controls.Add(_keyboardContainer);
// 3. 下方三大特色版面容器
_bottomPanelContainer = new TableLayoutPanel
{
Location = new Point(25, 470),
Size = new Size(1385, 235),
RowCount = 1,
ColumnCount = 3,
BackColor = Color.Transparent
};
_bottomPanelContainer.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 22f)); // 滑鼠診斷
_bottomPanelContainer.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 48f)); // 打字測試
_bottomPanelContainer.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 30f)); // 即時日誌
this.Controls.Add(_bottomPanelContainer);
// --- 3.1 滑鼠診斷區 ---
_mouseTester = new MouseTesterControl
{
Dock = DockStyle.Fill,
Margin = new Padding(0, 0, 10, 0)
};
_bottomPanelContainer.Controls.Add(_mouseTester, 0, 0);
// --- 3.2 打字測試區面板 ---
Panel typePanel = new Panel
{
Dock = DockStyle.Fill,
BackColor = Color.FromArgb(24, 24, 28),
Padding = new Padding(15),
Margin = new Padding(5, 0, 5, 0)
};
typePanel.Paint += (s, e) =>
e.Graphics.DrawRectangle(_panelBorderPen, 0, 0, typePanel.Width - 1, typePanel.Height - 1);
Label typeTitle = new Label
{
Text = "打字與延遲測試 (TYPING & LATENCY TEST)",
Font = new Font("Segoe UI", 9.5f, FontStyle.Bold),
ForeColor = Color.FromArgb(200, 200, 210),
Location = new Point(15, 10),
AutoSize = true
};
typePanel.Controls.Add(typeTitle);
_typeTextBox = new TextBox
{
Multiline = true,
BackColor = Color.FromArgb(18, 18, 22),
ForeColor = Color.FromArgb(245, 245, 250),
BorderStyle = BorderStyle.FixedSingle,
Font = new Font("Consolas", 10.5f),
Location = new Point(15, 35),
Size = new Size(625, 95),
TabStop = false
};
_typeTextBox.TextChanged += TypeTextBox_TextChanged;
_typeTextBox.KeyDown += (s, e) =>
{
if (e.KeyCode == Keys.Escape)
{
_typeTextBox.Clear();
e.SuppressKeyPress = true;
}
};
typePanel.Controls.Add(_typeTextBox);
// 速度指標容器
FlowLayoutPanel speedIndicators = new FlowLayoutPanel
{
Location = new Point(15, 140),
Size = new Size(625, 80),
FlowDirection = FlowDirection.LeftToRight,
WrapContents = false,
BackColor = Color.Transparent
};
_wpmLabel = CreateIndicatorLabel("WPM", () => GetWPMString(), Color.FromArgb(0, 242, 254));
_kpsLabel = CreateIndicatorLabel("當前 KPS", () => GetKpsString(false), Color.FromArgb(16, 185, 129));
_maxKpsLabel = CreateIndicatorLabel("最高 KPS", () => GetKpsString(true), Color.FromArgb(245, 158, 11));
_latencyLabel = CreateIndicatorLabel("按鍵持續時間", () => GetLastLatencyString(), Color.FromArgb(167, 139, 250));
speedIndicators.Controls.Add(_wpmLabel);
speedIndicators.Controls.Add(_kpsLabel);
speedIndicators.Controls.Add(_maxKpsLabel);
speedIndicators.Controls.Add(_latencyLabel);
typePanel.Controls.Add(speedIndicators);
_bottomPanelContainer.Controls.Add(typePanel, 1, 0);
// --- 3.3 即時日誌面板 ---
Panel logPanel = new Panel
{
Dock = DockStyle.Fill,
BackColor = Color.FromArgb(24, 24, 28),
Padding = new Padding(15),
Margin = new Padding(10, 0, 0, 0)
};
logPanel.Paint += (s, e) =>
e.Graphics.DrawRectangle(_panelBorderPen, 0, 0, logPanel.Width - 1, logPanel.Height - 1);
Label logTitle = new Label
{
Text = "實時按鍵日誌 (LIVE EVENT LOG)",
Font = new Font("Segoe UI", 9.5f, FontStyle.Bold),
ForeColor = Color.FromArgb(200, 200, 210),
Location = new Point(15, 10),
AutoSize = true
};
logPanel.Controls.Add(logTitle);
_logListBox = new ListBox
{
BackColor = Color.FromArgb(18, 18, 22),
ForeColor = Color.FromArgb(220, 220, 230),
BorderStyle = BorderStyle.FixedSingle,
Font = new Font("Consolas", 9f),
DrawMode = DrawMode.OwnerDrawFixed,
ItemHeight = 20,
Location = new Point(15, 35),
Size = new Size(385, 180),
TabStop = false
};
_logListBox.DrawItem += LogListBox_DrawItem;
logPanel.Controls.Add(_logListBox);
_bottomPanelContainer.Controls.Add(logPanel, 2, 0);
// 4. 底部提示資訊
_bottomTips = new Label
{
Text = "亮藍色代表目前按下 | 暗青色代表已測試過 | 紅色代表卡鍵 (>2秒) | 支援滑鼠點擊與滾輪檢測 | 按 ESC 可清空打字測試區",
Font = new Font("Segoe UI", 9.5f),
ForeColor = Color.FromArgb(130, 130, 140),
BackColor = Color.Transparent,
TextAlign = ContentAlignment.MiddleCenter,
Location = new Point(25, 712),
Size = new Size(1385, 25)
};
this.Controls.Add(_bottomTips);
// 5. 初始化與載入預設鍵盤
UpdateKeyboardLayout("100%");
// 6. 初始化卡鍵偵測看門狗計時器 (200ms)
_watchdogTimer = new Timer();
_watchdogTimer.Interval = 200;
_watchdogTimer.Tick += StuckWatchdog_Tick;
_watchdogTimer.Start();
// 7. 初始化 KPS 每秒統計 Timer
_kpsTimer = new Timer();
_kpsTimer.Interval = 1000;
_kpsTimer.Tick += KpsTimer_Tick;
_kpsTimer.Start();
}
private Label CreateIndicatorLabel(string name, Func<string> getValue, Color valueColor)
{
Label lbl = new Label
{
Size = new Size(150, 70),
BackColor = Color.FromArgb(18, 18, 22),
Margin = new Padding(0, 0, 5, 0),
Padding = new Padding(8)
};
// 此面板每秒/每次按鍵都會重繪,字型與邊框 Pen 使用表單快取的固定資源
lbl.Paint += (s, e) =>
{
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
// 畫邊框
e.Graphics.DrawRectangle(_indicatorBorderPen, 0, 0, lbl.Width - 1, lbl.Height - 1);
// 畫指標名稱
TextRenderer.DrawText(e.Graphics, name, _indicatorNameFont, new Rectangle(8, 6, lbl.Width - 16, 20), Color.FromArgb(130, 130, 140));
// 畫動態讀取的數值
string valueText = getValue();
TextRenderer.DrawText(e.Graphics, valueText, _indicatorValueFont, new Rectangle(8, 26, lbl.Width - 16, 35), valueColor, TextFormatFlags.VerticalCenter);
};
return lbl;
}
private static float GetKeySpan(string key)
{
key = key.ToUpperInvariant();
if (key == "SPACE") return 12f;
if (key == "SHIFT_L" || key == "SHIFT_R") return 5f;
if (key == "BACKSPACE" || key == "ENTER" || key == "CAPSLOCK") return 4f;
if (key == "TAB" || key == "CTRL_L" || key == "WIN" || key == "ALT_L" || key == "ALT_R" || key == "MENU" || key == "CTRL_R" || key == "\\") return 3f;
return 2f;
}
// 安裝與解除低階鉤子
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
_inputHook.KeyChanged += InputHook_KeyChanged;
_inputHook.MouseButtonChanged += InputHook_MouseButtonChanged;
_inputHook.MouseWheelScrolled += InputHook_MouseWheelScrolled;
_inputHook.CallbackError += InputHook_CallbackError;
try
{
_inputHook.Start();
}
catch (Win32Exception exception)
{
MessageBox.Show(
this,
$"無法安裝全域輸入監控 Hook(Win32 錯誤 {exception.NativeErrorCode})。程式將關閉。",
"初始化失敗",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
BeginInvoke(new Action(Close));
}
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
_inputHook.Stop();
_watchdogTimer?.Stop();
_kpsTimer?.Stop();
base.OnFormClosing(e);
}
protected override void Dispose(bool disposing)
{
_inputHook.Dispose();
if (disposing)
{
_watchdogTimer?.Dispose();
_kpsTimer?.Dispose();
_indicatorNameFont?.Dispose();
_indicatorValueFont?.Dispose();
_indicatorBorderPen?.Dispose();
_panelBorderPen?.Dispose();
_statusNormalBrush?.Dispose();
_statusStuckBrush?.Dispose();
_logDefaultBrush?.Dispose();
_logPressBrush?.Dispose();
_logReleaseBrush?.Dispose();
_logStuckBrush?.Dispose();
_logMouseBrush?.Dispose();
}
base.Dispose(disposing);
}
private void InputHook_KeyChanged(string keyName, bool isPressed)
{
if (isPressed)
{
OnKeyDownEvent(keyName);
}
else
{
OnKeyUpEvent(keyName);
}
}
private void InputHook_MouseButtonChanged(string buttonName, bool isPressed)
{
OnMouseChanged(buttonName, isPressed);
}
private void InputHook_MouseWheelScrolled(int delta)
{
OnMouseWheelScrolled(delta);
}
private void InputHook_CallbackError(Exception exception)
{
AddLog($"[Hook 錯誤] {exception.Message}");
}
private void OnKeyDownEvent(string keyName)
{
if (_keyStateTracker.Press(keyName))
{
_keyRateCounter.RecordPress();
UpdateKeyUI(keyName, KeyControl.KeyState.Pressed);
AddLog($"[按下] {keyName}");
}
}
private void OnKeyUpEvent(string keyName)
{
KeyReleaseResult release = _keyStateTracker.Release(keyName);
if (release.WasPressed)
{
UpdateKeyUI(keyName, KeyControl.KeyState.Tested);
string durationStr = release.DurationMilliseconds > 0
? $" (持續 {release.DurationMilliseconds:F0}ms)"
: "";
AddLog($"[放開] {keyName}{durationStr}");
if (release.DurationMilliseconds > 0)
{
_lastLatencyMs = release.DurationMilliseconds;
UpdateLatencyUI(release.DurationMilliseconds);
}
}
}
private void StuckWatchdog_Tick(object sender, EventArgs e)
{
IReadOnlyList<string> stuckKeys = _keyStateTracker.MarkStuck(TimeSpan.FromSeconds(2));
foreach (var keyName in stuckKeys)
{
UpdateKeyUI(keyName, KeyControl.KeyState.Stuck);
AddLog($"[卡鍵] {keyName} (已按住 >2秒!)");
}
}
private void KpsTimer_Tick(object sender, EventArgs e)
{
int kps = _keyRateCounter.Sample();
if (this.InvokeRequired)
{
this.BeginInvoke(new Action(() => UpdateKpsUI(kps)));
}
else
{
UpdateKpsUI(kps);
}
}
private void UpdateKpsUI(int kps)
{
_kpsLabel.Invalidate();
_maxKpsLabel.Invalidate();
_wpmLabel.Invalidate();
}
private void UpdateLatencyUI(double durationMs)
{
if (this.InvokeRequired)
{
this.BeginInvoke(new Action(() => UpdateLatencyUI(durationMs)));
return;
}
_latencyLabel.Invalidate();
}
private void TypeTextBox_TextChanged(object sender, EventArgs e)
{
_typingMetrics.ObserveCharacterCount(_typeTextBox.TextLength);
_wpmLabel.Invalidate();
}
private void UpdateKeyUI(string keyName, KeyControl.KeyState state)
{
if (this.InvokeRequired)
{
this.BeginInvoke(new Action(() => UpdateKeyUI(keyName, state)));
return;
}
if (keyName != null && _keyControls.TryGetValue(keyName, out KeyControl ctrl))
{
ctrl.State = state;
}
KeyStateSnapshot snapshot = _keyStateTracker.GetSnapshot();
int pressedCount = snapshot.ActiveKeyCount;
IReadOnlyList<string> stuckKeys = snapshot.StuckKeys;
_countLabel.Text = $"當前按下鍵數: {pressedCount}";
if (stuckKeys.Count > 0)
{
_statusLight.BackColor = _statusStuckBrush.Color;
_statusText.Text = $"警告:偵測到卡鍵!({string.Join(", ", stuckKeys)})";
_statusText.ForeColor = _statusStuckBrush.Color;
}
else
{
_statusLight.BackColor = _statusNormalBrush.Color;
_statusText.ForeColor = _statusNormalBrush.Color;
_statusText.Text = pressedCount > 0
? $"偵測中 - 同時按下 {pressedCount} 個鍵"
: "系統偵測中 - 正常";
}
_statusLight.Invalidate();
}
private void ResetAll()
{
_keyStateTracker.Reset();
_keyRateCounter.Reset();
_typingMetrics.Reset();
_lastLatencyMs = 0;
foreach (var ctrl in _keyControls.Values)
{
ctrl.State = KeyControl.KeyState.Untested;
}
_typeTextBox.Clear();
_logListBox.Items.Clear();
_mouseTester.ResetMouse();
_wpmLabel.Invalidate();
_kpsLabel.Invalidate();
_maxKpsLabel.Invalidate();
_latencyLabel.Invalidate();
UpdateKeyUI(null, KeyControl.KeyState.Untested);
AddLog("--- 所有診斷狀態已重置 ---");
}
private void AddLog(string msg)
{
if (this.InvokeRequired)
{
this.BeginInvoke(new Action(() => AddLog(msg)));
return;
}
string timestamp = DateTime.Now.ToString("HH:mm:ss.fff", CultureInfo.InvariantCulture);
_logListBox.Items.Add($"[{timestamp}] {msg}");
_logListBox.TopIndex = _logListBox.Items.Count - 1;
if (_logListBox.Items.Count > 100)
{
_logListBox.Items.RemoveAt(0);
}
}
public void OnMouseChanged(string btnName, bool isPressed)
{
if (InvokeRequired)
{
BeginInvoke(new Action(() => OnMouseChanged(btnName, isPressed)));
return;
}
if (btnName == "L_BUTTON") _mouseTester.LPressed = isPressed;
else if (btnName == "R_BUTTON") _mouseTester.RPressed = isPressed;
else if (btnName == "M_BUTTON") _mouseTester.MPressed = isPressed;
else if (btnName == "X1_BUTTON") _mouseTester.X1Pressed = isPressed;
else if (btnName == "X2_BUTTON") _mouseTester.X2Pressed = isPressed;
_mouseTester.Invalidate();
string status = isPressed ? "按下" : "放開";
AddLog($"[滑鼠] {btnName} {status}");
}
public void OnMouseWheelScrolled(int delta)
{
if (InvokeRequired)
{
BeginInvoke(new Action(() => OnMouseWheelScrolled(delta)));
return;
}
_mouseTester.RegisterScroll(delta);
string dir = delta > 0 ? "向上" : "向下";
AddLog($"[滑鼠] 滾輪 {dir}");
}
private void KeyboardTypeSelector_SelectedIndexChanged(object sender, EventArgs e)
{
string selected = _keyboardTypeSelector.SelectedItem.ToString();
string type = "100%";
if (selected.Contains("80%", StringComparison.Ordinal)) type = "80%";
else if (selected.Contains("60%", StringComparison.Ordinal)) type = "60%";
UpdateKeyboardLayout(type);
}
private void UpdateKeyboardLayout(string type)
{
ResetAll();
_keyboardContainer.Width = this.ClientSize.Width - 50;
_bottomPanelContainer.Width = this.ClientSize.Width - 50;
_bottomTips.Width = this.ClientSize.Width - 50;
_keyboardContainer.ColumnStyles.Clear();
_keyboardContainer.Controls.Clear();
_keyControls.Clear();
if (type == "60%")
{
_keyboardContainer.ColumnCount = 1;
_keyboardContainer.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100f));
}
else if (type == "80%")
{
_keyboardContainer.ColumnCount = 2;
_keyboardContainer.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 78f));
_keyboardContainer.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 22f));
}
else
{
_keyboardContainer.ColumnCount = 3;
_keyboardContainer.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 64f));
_keyboardContainer.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 17f));
_keyboardContainer.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 19f));
}
var main = CreateMainKeyboard();
_keyboardContainer.Controls.Add(main, 0, 0);
if (type == "80%" || type == "100%")
{
var nav = CreateNavKeyboard();
_keyboardContainer.Controls.Add(nav, 1, 0);
}
if (type == "100%")
{
var num = CreateNumKeyboard();
_keyboardContainer.Controls.Add(num, 2, 0);
}
}
private TableLayoutPanel CreateMainKeyboard()
{
TableLayoutPanel mainCard = new TableLayoutPanel
{
Dock = DockStyle.Fill,
Margin = new Padding(0),
RowCount = MAIN_LAYOUT.Length,
ColumnCount = 1,
BackColor = Color.Transparent
};
for (int r = 0; r < MAIN_LAYOUT.Length; r++)
{
mainCard.RowStyles.Add(new RowStyle(SizeType.Percent, 100f / MAIN_LAYOUT.Length));
}
for (int r = 0; r < MAIN_LAYOUT.Length; r++)
{
string[] rowKeys = MAIN_LAYOUT[r];
TableLayoutPanel rowPanel = new TableLayoutPanel
{
BackColor = Color.Transparent,
Dock = DockStyle.Fill,
Margin = new Padding(0, 4, 0, 4),
RowCount = 1,
ColumnCount = rowKeys.Length
};
rowPanel.RowStyles.Add(new RowStyle(SizeType.Percent, 100f));
float totalSpan = rowKeys.Sum(k => GetKeySpan(k));
for (int c = 0; c < rowKeys.Length; c++)
{
string key = rowKeys[c];
float span = GetKeySpan(key);
float percent = (span / totalSpan) * 100f;
rowPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, percent));
KeyControl keyCtrl = new KeyControl
{
KeyText = key,
AccessibleName = key,
Dock = DockStyle.Fill,
Margin = new Padding(3, 2, 3, 2)
};
rowPanel.Controls.Add(keyCtrl, c, 0);
_keyControls[key] = keyCtrl;
}
mainCard.Controls.Add(rowPanel, 0, r);
}
return mainCard;
}
private TableLayoutPanel CreateNavKeyboard()
{
TableLayoutPanel navCard = new TableLayoutPanel
{
Dock = DockStyle.Fill,
Margin = new Padding(10, 0, 0, 0),
RowCount = NAV_LAYOUT.Length,
ColumnCount = NAV_LAYOUT[0].Length,
BackColor = Color.Transparent
};
for (int r = 0; r < NAV_LAYOUT.Length; r++)
{
navCard.RowStyles.Add(new RowStyle(SizeType.Percent, 100f / NAV_LAYOUT.Length));
}
for (int c = 0; c < NAV_LAYOUT[0].Length; c++)
{
navCard.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100f / NAV_LAYOUT[0].Length));
}
for (int r = 0; r < NAV_LAYOUT.Length; r++)
{
for (int c = 0; c < NAV_LAYOUT[r].Length; c++)
{
string key = NAV_LAYOUT[r][c];
if (string.IsNullOrEmpty(key)) continue;
KeyControl keyCtrl = new KeyControl
{
KeyText = key,
AccessibleName = key,
Dock = DockStyle.Fill,
Margin = new Padding(3, 4, 3, 4)
};
navCard.Controls.Add(keyCtrl, c, r);
_keyControls[key] = keyCtrl;
}
}
return navCard;
}
private TableLayoutPanel CreateNumKeyboard()
{
TableLayoutPanel numCard = new TableLayoutPanel
{
Dock = DockStyle.Fill,
Margin = new Padding(15, 0, 0, 0),
RowCount = NUM_LAYOUT.Length,
ColumnCount = NUM_LAYOUT[0].Length,
BackColor = Color.Transparent
};
for (int r = 0; r < NUM_LAYOUT.Length; r++)
{
numCard.RowStyles.Add(new RowStyle(SizeType.Percent, 100f / NUM_LAYOUT.Length));
}
for (int c = 0; c < NUM_LAYOUT[0].Length; c++)
{
numCard.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100f / NUM_LAYOUT[0].Length));
}
bool[,] occupied = new bool[NUM_LAYOUT.Length, NUM_LAYOUT[0].Length];
for (int r = 0; r < NUM_LAYOUT.Length; r++)
{
for (int c = 0; c < NUM_LAYOUT[r].Length; c++)
{
if (occupied[r, c]) continue;
string key = NUM_LAYOUT[r][c];
if (string.IsNullOrEmpty(key)) continue;
int rowSpan = 1;
int colSpan = 1;
if (key == "NUM_+")
{
rowSpan = 2;
occupied[r, c] = true;
occupied[r + 1, c] = true;
}
else if (key == "NUM_ENTER")
{
rowSpan = 2;
occupied[r, c] = true;
occupied[r + 1, c] = true;
}
else if (key == "NUM_0")
{
colSpan = 2;
occupied[r, c] = true;
occupied[r, c + 1] = true;
}
else
{
occupied[r, c] = true;
}
KeyControl keyCtrl = new KeyControl
{
KeyText = key,
AccessibleName = key,
Dock = DockStyle.Fill,
Margin = new Padding(3, 4, 3, 4)
};
numCard.Controls.Add(keyCtrl, c, r);
if (rowSpan > 1) numCard.SetRowSpan(keyCtrl, rowSpan);
if (colSpan > 1) numCard.SetColumnSpan(keyCtrl, colSpan);
_keyControls[key] = keyCtrl;
}
}
return numCard;
}
private void LogListBox_DrawItem(object sender, DrawItemEventArgs e)
{
if (e.Index < 0) return;
e.DrawBackground();
string text = _logListBox.Items[e.Index].ToString();
SolidBrush textBrush = _logDefaultBrush;
if (text.Contains("[按下]", StringComparison.Ordinal))
{
textBrush = _logPressBrush;
}
else if (text.Contains("[放開]", StringComparison.Ordinal))
{
textBrush = _logReleaseBrush;
}
else if (text.Contains("[卡鍵]", StringComparison.Ordinal))
{
textBrush = _logStuckBrush;
}
else if (text.Contains("[滑鼠]", StringComparison.Ordinal))
{
textBrush = _logMouseBrush;
}
e.Graphics.DrawString(text, e.Font, textBrush, e.Bounds.X + 5, e.Bounds.Y + 2);
e.DrawFocusRectangle();
}
public string GetWPMString()
{
return _typingMetrics.CalculateWordsPerMinute(_typeTextBox.TextLength)
.ToString(CultureInfo.InvariantCulture);
}
public string GetKpsString(bool getMax = false)
{
return (getMax ? _keyRateCounter.Peak : _keyRateCounter.LastSample).ToString(CultureInfo.InvariantCulture);
}
public string GetLastLatencyString()
{
return _lastLatencyMs > 0 ? $"{_lastLatencyMs:F0} ms" : "-- ms";
}
}
public class KeyControl : Control
{
public enum KeyState
{
Untested,
Pressed,
Tested,
Stuck
}
// 邊框顏色只有四種固定狀態;以應用程式生命週期的靜態 Pen 陣列共用,避免每次重繪配置/釋放
private static readonly Pen[] BorderPens =
{
new Pen(Color.FromArgb(52, 52, 60), 1.5f), // Untested
new Pen(Color.FromArgb(0, 190, 255), 1.5f), // Pressed
new Pen(Color.FromArgb(14, 116, 144), 1.5f), // Tested
new Pen(Color.FromArgb(220, 38, 38), 1.5f), // Stuck
};
private static Pen GetBorderPen(KeyState state)