-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKeyboardMonitor.cs
More file actions
1586 lines (1398 loc) · 58.7 KB
/
Copy pathKeyboardMonitor.cs
File metadata and controls
1586 lines (1398 loc) · 58.7 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.Runtime.InteropServices;
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 sealed class KeyStateInfo
{
public string Status { get; set; }
public DateTime PressedTime { get; set; }
}
// 狀態字典與執行緒安全鎖
private readonly Dictionary<string, KeyStateInfo> _keyStates = new Dictionary<string, KeyStateInfo>();
private readonly object _stateLock = new object();
// 記錄按鍵按下時間戳,用以計算按壓延遲 (持續時間)
private readonly Dictionary<string, DateTime> _keyPressStartTimes = new Dictionary<string, DateTime>();
// 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 DateTime? _typingStartTime;
private readonly KeyRateCounter _keyRateCounter = new KeyRateCounter();
private double _lastLatencyMs;
private Timer _kpsTimer;
// Windows Hook API 宣告
private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
private delegate IntPtr LowLevelMouseProc(int nCode, IntPtr wParam, IntPtr lParam);
[DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
[DllImport("user32.dll", EntryPoint = "SetWindowsHookEx", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr SetKeyboardHook(int idHook, LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);
[DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
[DllImport("user32.dll", EntryPoint = "SetWindowsHookEx", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr SetMouseHook(int idHook, LowLevelMouseProc lpfn, IntPtr hMod, uint dwThreadId);
[DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool UnhookWindowsHookEx(IntPtr hhk);
[DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);
[DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
[DllImport("kernel32.dll", EntryPoint = "GetModuleHandleW", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern IntPtr GetModuleHandle(string lpModuleName);
[StructLayout(LayoutKind.Sequential)]
private struct KBDLLHOOKSTRUCT
{
public uint vkCode;
public uint scanCode;
public uint flags;
public uint time;
public IntPtr dwExtraInfo;
}
[StructLayout(LayoutKind.Sequential)]
private struct POINT
{
public int x;
public int y;
}
[StructLayout(LayoutKind.Sequential)]
private struct MSLLHOOKSTRUCT
{
public POINT pt;
public uint mouseData;
public uint flags;
public uint time;
public IntPtr dwExtraInfo;
}
private const int WH_KEYBOARD_LL = 13;
private const int WH_MOUSE_LL = 14;
private const int WM_KEYDOWN = 0x0100;
private const int WM_KEYUP = 0x0101;
private const int WM_SYSKEYDOWN = 0x0104;
private const int WM_SYSKEYUP = 0x0105;
private const int WM_LBUTTONDOWN = 0x0201;
private const int WM_LBUTTONUP = 0x0202;
private const int WM_RBUTTONDOWN = 0x0204;
private const int WM_RBUTTONUP = 0x0205;
private const int WM_MBUTTONDOWN = 0x0207;
private const int WM_MBUTTONUP = 0x0208;
private const int WM_MOUSEWHEEL = 0x020A;
private const int WM_XBUTTONDOWN = 0x020B;
private const int WM_XBUTTONUP = 0x020C;
private IntPtr _hookID = IntPtr.Zero;
private IntPtr _mouseHookID = IntPtr.Zero;
private LowLevelKeyboardProc _proc;
private LowLevelMouseProc _mouseProc;
[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 = Color.FromArgb(0x10, 0xB9, 0x81), // 精緻綠
Margin = new Padding(5, 6, 5, 0)
};
// 繪製圓形指示燈
_statusLight.Paint += (s, e) =>
{
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
using (SolidBrush b = new SolidBrush(_statusLight.BackColor))
{
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 = Color.FromArgb(0x10, 0xB9, 0x81),
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
};
// 繪製容器邊框
_keyboardContainer.Paint += (s, e) =>
{
using (Pen p = new Pen(Color.FromArgb(45, 45, 52), 1f))
{
e.Graphics.DrawRectangle(p, 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) =>
{
using (Pen p = new Pen(Color.FromArgb(45, 45, 52), 1f))
e.Graphics.DrawRectangle(p, 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) =>
{
using (Pen p = new Pen(Color.FromArgb(45, 45, 52), 1f))
e.Graphics.DrawRectangle(p, 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 static 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)
};
lbl.Paint += (s, e) =>
{
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
// 畫邊框
using (Pen p = new Pen(Color.FromArgb(40, 40, 48), 1f))
{
e.Graphics.DrawRectangle(p, 0, 0, lbl.Width - 1, lbl.Height - 1);
}
// 畫指標名稱
using (Font nameFont = new Font("Segoe UI", 8.5f, FontStyle.Regular))
{
TextRenderer.DrawText(e.Graphics, name, nameFont, new Rectangle(8, 6, lbl.Width - 16, 20), Color.FromArgb(130, 130, 140));
}
// 畫動態讀取的數值
string valueText = getValue();
using (Font valFont = new Font("Segoe UI", 13f, FontStyle.Bold))
{
TextRenderer.DrawText(e.Graphics, valueText, valFont, 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);
_proc = HookCallback;
_mouseProc = MouseHookCallback;
_hookID = SetHook(_proc);
_mouseHookID = SetHook(_mouseProc);
if (_hookID == IntPtr.Zero || _mouseHookID == IntPtr.Zero)
{
int errorCode = Marshal.GetLastWin32Error();
ReleaseHooks();
MessageBox.Show(
this,
$"無法安裝全域輸入監控 Hook(Win32 錯誤 {errorCode})。程式將關閉。",
"初始化失敗",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
BeginInvoke(new Action(Close));
}
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
ReleaseHooks();
_watchdogTimer?.Stop();
_kpsTimer?.Stop();
base.OnFormClosing(e);
}
protected override void Dispose(bool disposing)
{
ReleaseHooks();
if (disposing)
{
_watchdogTimer?.Dispose();
_kpsTimer?.Dispose();
}
base.Dispose(disposing);
}
private static IntPtr SetHook(LowLevelKeyboardProc proc)
{
using (System.Diagnostics.Process curProcess = System.Diagnostics.Process.GetCurrentProcess())
using (System.Diagnostics.ProcessModule curModule = curProcess.MainModule)
{
return SetKeyboardHook(WH_KEYBOARD_LL, proc, GetModuleHandle(curModule.ModuleName), 0);
}
}
private static IntPtr SetHook(LowLevelMouseProc proc)
{
using (System.Diagnostics.Process curProcess = System.Diagnostics.Process.GetCurrentProcess())
using (System.Diagnostics.ProcessModule curModule = curProcess.MainModule)
{
return SetMouseHook(WH_MOUSE_LL, proc, GetModuleHandle(curModule.ModuleName), 0);
}
}
private void ReleaseHooks()
{
if (_hookID != IntPtr.Zero)
{
UnhookWindowsHookEx(_hookID);
_hookID = IntPtr.Zero;
}
if (_mouseHookID != IntPtr.Zero)
{
UnhookWindowsHookEx(_mouseHookID);
_mouseHookID = IntPtr.Zero;
}
}
private IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode >= 0)
{
long message = (long)wParam;
if (message == WM_KEYDOWN || message == WM_SYSKEYDOWN)
{
KBDLLHOOKSTRUCT kb = Marshal.PtrToStructure<KBDLLHOOKSTRUCT>(lParam);
string keyName = KeyboardInput.ParseKey(kb.vkCode, kb.scanCode, kb.flags);
if (keyName != null)
{
OnKeyDownEvent(keyName);
}
}
else if (message == WM_KEYUP || message == WM_SYSKEYUP)
{
KBDLLHOOKSTRUCT kb = Marshal.PtrToStructure<KBDLLHOOKSTRUCT>(lParam);
string keyName = KeyboardInput.ParseKey(kb.vkCode, kb.scanCode, kb.flags);
if (keyName != null)
{
OnKeyUpEvent(keyName);
}
}
}
return CallNextHookEx(_hookID, nCode, wParam, lParam);
}
private IntPtr MouseHookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode >= 0)
{
int message = unchecked((int)(long)wParam);
MSLLHOOKSTRUCT mouseData = Marshal.PtrToStructure<MSLLHOOKSTRUCT>(lParam);
switch (message)
{
case WM_LBUTTONDOWN:
OnMouseChanged("L_BUTTON", true);
break;
case WM_LBUTTONUP:
OnMouseChanged("L_BUTTON", false);
break;
case WM_RBUTTONDOWN:
OnMouseChanged("R_BUTTON", true);
break;
case WM_RBUTTONUP:
OnMouseChanged("R_BUTTON", false);
break;
case WM_MBUTTONDOWN:
OnMouseChanged("M_BUTTON", true);
break;
case WM_MBUTTONUP:
OnMouseChanged("M_BUTTON", false);
break;
case WM_XBUTTONDOWN:
case WM_XBUTTONUP:
int xButton = (int)((mouseData.mouseData >> 16) & 0xFFFF);
OnMouseChanged(
xButton == 1 ? "X1_BUTTON" : "X2_BUTTON",
message == WM_XBUTTONDOWN);
break;
case WM_MOUSEWHEEL:
short delta = unchecked((short)((mouseData.mouseData >> 16) & 0xFFFF));
OnMouseWheelScrolled(delta);
break;
}
}
return CallNextHookEx(_mouseHookID, nCode, wParam, lParam);
}
private void OnKeyDownEvent(string keyName)
{
bool isNewPress = false;
lock (_stateLock)
{
if (!_keyStates.TryGetValue(keyName, out KeyStateInfo state) || state.Status != "pressed")
{
_keyStates[keyName] = new KeyStateInfo
{
Status = "pressed",
PressedTime = DateTime.Now
};
_keyPressStartTimes[keyName] = DateTime.Now;
isNewPress = true;
_keyRateCounter.RecordPress();
}
}
if (isNewPress)
{
UpdateKeyUI(keyName, KeyControl.KeyState.Pressed);
AddLog($"[按下] {keyName}");
}
}
private void OnKeyUpEvent(string keyName)
{
double durationMs = 0;
bool isReleased = false;
lock (_stateLock)
{
isReleased = _keyStates.Remove(keyName);
if (_keyPressStartTimes.TryGetValue(keyName, out DateTime pressTime))
{
durationMs = (DateTime.Now - pressTime).TotalMilliseconds;
_keyPressStartTimes.Remove(keyName);
}
}
if (isReleased)
{
UpdateKeyUI(keyName, KeyControl.KeyState.Tested);
string durationStr = durationMs > 0 ? $" (持續 {durationMs:F0}ms)" : "";
AddLog($"[放開] {keyName}{durationStr}");
if (durationMs > 0)
{
_lastLatencyMs = durationMs;
UpdateLatencyUI(durationMs);
}
}
}
private void StuckWatchdog_Tick(object sender, EventArgs e)
{
DateTime now = DateTime.Now;
List<string> stuckKeys = new List<string>();
lock (_stateLock)
{
foreach (var pair in _keyStates)
{
if (pair.Value.Status == "pressed" && (now - pair.Value.PressedTime).TotalSeconds > 2.0)
{
stuckKeys.Add(pair.Key);
}
}
}
foreach (var keyName in stuckKeys)
{
UpdateKeyUI(keyName, KeyControl.KeyState.Stuck);
lock (_stateLock)
{
if (_keyStates.TryGetValue(keyName, out KeyStateInfo state) && state.Status == "pressed")
{
state.Status = "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();
}
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)
{
if (string.IsNullOrEmpty(_typeTextBox.Text))
{
_typingStartTime = null;
_wpmLabel.Invalidate();
return;
}
if (_typingStartTime == null)
{
_typingStartTime = DateTime.Now;
}
_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;
}
int pressedCount = 0;
List<string> stuckKeys = new List<string>();
DateTime now = DateTime.Now;
lock (_stateLock)
{
pressedCount = _keyStates.Count(x => x.Value.Status == "pressed" || x.Value.Status == "stuck");
foreach (var pair in _keyStates)
{
if ((now - pair.Value.PressedTime).TotalSeconds > 2.0)
{
stuckKeys.Add(pair.Key);
}
}
}
_countLabel.Text = $"當前按下鍵數: {pressedCount}";
if (stuckKeys.Count > 0)
{
_statusLight.BackColor = Color.FromArgb(0xEF, 0x44, 0x44);
_statusText.Text = $"警告:偵測到卡鍵!({string.Join(", ", stuckKeys)})";
_statusText.ForeColor = Color.FromArgb(0xEF, 0x44, 0x44);
}
else
{
if (pressedCount > 0)
{
_statusLight.BackColor = Color.FromArgb(0x10, 0xB9, 0x81);
_statusText.Text = $"偵測中 - 同時按下 {pressedCount} 個鍵";
_statusText.ForeColor = Color.FromArgb(0x10, 0xB9, 0x81);
}
else
{
_statusLight.BackColor = Color.FromArgb(0x10, 0xB9, 0x81);
_statusText.Text = "系統偵測中 - 正常";
_statusText.ForeColor = Color.FromArgb(0x10, 0xB9, 0x81);
}
}
_statusLight.Invalidate();
}
private void ResetAll()
{
lock (_stateLock)
{
_keyStates.Clear();
_keyPressStartTimes.Clear();
}
_keyRateCounter.Reset();
_typingStartTime = null;
_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