Repository navigation
Expand file tree
/
Copy pathKeyForge.py
More file actions
1636 lines (1375 loc) · 69 KB
/
Copy pathKeyForge.py
File metadata and controls
1636 lines (1375 loc) · 69 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
import sys
import os
import json
import threading
import time
import ctypes
import ctypes.wintypes
import win32gui
import win32con
import win32api
import win32process
import win32event
import struct
import psutil # 需要安装: pip install psutil
from PySide6.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout,
QHBoxLayout, QListWidget, QListWidgetItem, QCheckBox,
QPushButton, QComboBox, QGroupBox, QLabel, QProgressBar,
QMessageBox, QFileDialog, QSpinBox, QDoubleSpinBox,
QTextEdit, QSplitter, QGridLayout, QLineEdit, QRadioButton,
QButtonGroup)
from PySide6.QtCore import Qt, QSettings, Signal, QThread, QTimer
from PySide6.QtGui import QIcon, QFont, QColor
# 全局调试标志 - 编译后设置为False,不再输出到控制台
DEBUG_TO_CONSOLE = False # 编译后设置为False,避免控制台错误
def console_print(*args, **kwargs):
"""输出到控制台 - 编译后不执行任何操作"""
if DEBUG_TO_CONSOLE:
try:
print(*args, **kwargs)
sys.stdout.flush()
except:
pass
# 后台按键发送方式枚举 - 只保留完整实现的方法
class BackendKeyMethod:
# 基础消息方式 (0-9)
SENDMESSAGE = 0 # SendMessage WM_KEYDOWN/UP
POSTMESSAGE = 1 # PostMessage WM_KEYDOWN/UP
KEYBD_EVENT = 2 # keybd_event (全局)
SENDINPUT = 3 # SendInput (高级输入)
WM_KEYDOWN_DIRECT = 4 # WM_KEYDOWN直接发送
WM_CHAR = 5 # WM_CHAR字符消息
WM_IME_CHAR = 6 # WM_IME_CHAR输入法字符
WM_SYSKEYDOWN = 7 # WM_SYSKEYDOWN系统按键
POSTMESSAGE_LPARAM = 8 # PostMessage带完整lParam
# 高级消息方式 (10-19)
WM_HOTKEY = 10 # WM_HOTKEY热键消息
WM_APPCOMMAND = 11 # WM_APPCOMMAND应用程序命令
SENDMESSAGE_TIMEOUT = 12 # SendMessageTimeout
BROADCAST_MSG = 13 # BroadcastSystemMessage
# 输入模拟方式 (20-29)
ATTACH_THREAD = 20 # AttachThreadInput方式
SCAN_CODE = 21 # 扫描码方式
EXTENDED_KEY = 22 # 扩展键标志
# 特殊应用方式 (30-39)
WM_COPYDATA = 30 # WM_COPYDATA数据复制
CLIPBOARD = 31 # 剪贴板方式
COM_OBJECT = 32 # COM对象调用
# 获取方式总数
@classmethod
def get_total_count(cls):
"""获取所有方式的数量"""
return 33
@classmethod
def get_method_name(cls, method):
"""获取发送方式的名称"""
method_names = {
cls.SENDMESSAGE: "SendMessage (WM_KEY)",
cls.POSTMESSAGE: "PostMessage (WM_KEY)",
cls.KEYBD_EVENT: "keybd_event (全局)",
cls.SENDINPUT: "SendInput (高级输入)",
cls.WM_KEYDOWN_DIRECT: "WM_KEYDOWN直接发送",
cls.WM_CHAR: "WM_CHAR字符消息",
cls.WM_IME_CHAR: "WM_IME_CHAR输入法字符",
cls.WM_SYSKEYDOWN: "WM_SYSKEYDOWN系统按键",
cls.POSTMESSAGE_LPARAM: "PostMessage完整参数",
cls.WM_HOTKEY: "WM_HOTKEY热键消息",
cls.WM_APPCOMMAND: "WM_APPCOMMAND命令",
cls.SENDMESSAGE_TIMEOUT: "SendMessageTimeout",
cls.BROADCAST_MSG: "BroadcastSystemMessage",
cls.ATTACH_THREAD: "AttachThreadInput",
cls.SCAN_CODE: "扫描码方式",
cls.EXTENDED_KEY: "扩展键标志",
cls.WM_COPYDATA: "WM_COPYDATA",
cls.CLIPBOARD: "剪贴板方式",
cls.COM_OBJECT: "COM对象调用",
}
return method_names.get(method, f"未知方式({method})")
# 窗口枚举方式枚举
class EnumMethod:
BY_TITLE = 0 # 按窗口标题
BY_PROCESS = 1 # 按程序名
BY_BOTH = 2 # 两者兼顾(标题和程序名都匹配)
BY_CLASS = 3 # 按窗口类名
BY_PID = 4 # 按进程ID
BY_HANDLE = 5 # 按窗口句柄
# 按键映射表 - 完整版
KEY_MAP = {
# 字母键
"A": 0x41, "B": 0x42, "C": 0x43, "D": 0x44, "E": 0x45,
"F": 0x46, "G": 0x47, "H": 0x48, "I": 0x49, "J": 0x4A,
"K": 0x4B, "L": 0x4C, "M": 0x4D, "N": 0x4E, "O": 0x4F,
"P": 0x50, "Q": 0x51, "R": 0x52, "S": 0x53, "T": 0x54,
"U": 0x55, "V": 0x56, "W": 0x57, "X": 0x58, "Y": 0x59, "Z": 0x5A,
# 数字键
"0": 0x30, "1": 0x31, "2": 0x32, "3": 0x33, "4": 0x34,
"5": 0x35, "6": 0x36, "7": 0x37, "8": 0x38, "9": 0x39,
# 功能键
"F1": 0x70, "F2": 0x71, "F3": 0x72, "F4": 0x73, "F5": 0x74,
"F6": 0x75, "F7": 0x76, "F8": 0x77, "F9": 0x78, "F10": 0x79,
"F11": 0x7A, "F12": 0x7B, "F13": 0x7C, "F14": 0x7D, "F15": 0x7E,
"F16": 0x7F, "F17": 0x80, "F18": 0x81, "F19": 0x82, "F20": 0x83,
"F21": 0x84, "F22": 0x85, "F23": 0x86, "F24": 0x87,
# 控制键
"Space": 0x20, "Enter": 0x0D, "Esc": 0x1B, "Tab": 0x09,
"Backspace": 0x08, "Delete": 0x2E, "Insert": 0x2D,
"Home": 0x24, "End": 0x23, "PageUp": 0x21, "PageDown": 0x22,
"Print": 0x2C, "Pause": 0x13, "Cancel": 0x03, "Clear": 0x0C,
"Select": 0x29, "Execute": 0x2B, "Help": 0x2F,
# 方向键
"Up": 0x26, "Down": 0x28, "Left": 0x25, "Right": 0x27,
# 修饰键
"Ctrl": 0x11, "Alt": 0x12, "Shift": 0x10, "Win": 0x5B,
"RWin": 0x5C, "Apps": 0x5D,
# 小键盘
"Num0": 0x60, "Num1": 0x61, "Num2": 0x62, "Num3": 0x63,
"Num4": 0x64, "Num5": 0x65, "Num6": 0x66, "Num7": 0x67,
"Num8": 0x68, "Num9": 0x69,
"NumMult": 0x6A, "NumPlus": 0x6B, "NumMinus": 0x6D,
"NumDot": 0x6E, "NumDiv": 0x6F,
"NumEnter": 0x0D, "NumLock": 0x90,
# 多媒体键
"VolumeUp": 0xAF, "VolumeDown": 0xAE, "VolumeMute": 0xAD,
"MediaNext": 0xB0, "MediaPrev": 0xB1, "MediaStop": 0xB2,
"MediaPlayPause": 0xB3, "LaunchMail": 0xB4, "LaunchMedia": 0xB5,
"LaunchApp1": 0xB6, "LaunchApp2": 0xB7,
# 浏览器键
"BrowserBack": 0xA6, "BrowserForward": 0xA7, "BrowserRefresh": 0xA8,
"BrowserStop": 0xA9, "BrowserSearch": 0xAA, "BrowserFavorites": 0xAB,
"BrowserHome": 0xAC,
# 其他常用键
"CapsLock": 0x14, "PrintScreen": 0x2C, "ScrollLock": 0x91,
"PauseBreak": 0x13, "Menu": 0x5D, "Sleep": 0x5F,
# 符号键
"`": 0xC0, "-": 0xBD, "=": 0xBB, "[": 0xDB, "]": 0xDD,
"\\": 0xDC, ";": 0xBA, "'": 0xDE, ",": 0xBC, ".": 0xBE,
"/": 0xBF,
}
# 组合键映射表
MODIFIER_KEYS = {
"Ctrl": 0x11,
"Alt": 0x12,
"Shift": 0x10,
"Win": 0x5B,
"RWin": 0x5C,
}
# 按键显示名称列表(用于下拉框)
KEY_LIST = [
# 字母
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
"K", "L", "M", "N", "O", "P", "Q", "R", "S", "T",
"U", "V", "W", "X", "Y", "Z",
# 数字
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
# 功能键
"F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12",
"F13", "F14", "F15", "F16", "F17", "F18", "F19", "F20", "F21", "F22", "F23", "F24",
# 方向键
"Up", "Down", "Left", "Right",
# 控制键
"Space", "Enter", "Esc", "Tab", "Backspace", "Delete", "Insert",
"Home", "End", "PageUp", "PageDown", "Print", "Pause", "Cancel", "Clear",
"Select", "Execute", "Help",
# 修饰键
"Ctrl", "Alt", "Shift", "Win", "RWin", "Apps",
# 小键盘
"Num0", "Num1", "Num2", "Num3", "Num4", "Num5", "Num6", "Num7", "Num8", "Num9",
"NumMult", "NumPlus", "NumMinus", "NumDot", "NumDiv", "NumEnter", "NumLock",
# 多媒体键
"VolumeUp", "VolumeDown", "VolumeMute", "MediaNext", "MediaPrev",
"MediaStop", "MediaPlayPause", "LaunchMail", "LaunchMedia", "LaunchApp1", "LaunchApp2",
# 浏览器键
"BrowserBack", "BrowserForward", "BrowserRefresh", "BrowserStop",
"BrowserSearch", "BrowserFavorites", "BrowserHome",
# 符号键
"`", "-", "=", "[", "]", "\\", ";", "'", ",", ".", "/",
# 其他
"CapsLock", "PrintScreen", "ScrollLock", "PauseBreak", "Menu", "Sleep"
]
def get_all_process_names_from_hwnd(hwnd):
"""通过窗口句柄获取进程的所有信息(更可靠)"""
result = {
'process_name': '',
'process_path': '',
'process_cmdline': '',
'modules': [],
'pid': 0
}
try:
pid = win32process.GetWindowThreadProcessId(hwnd)[0]
result['pid'] = pid
PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
kernel32 = ctypes.windll.kernel32
psapi = ctypes.windll.psapi
hProcess = kernel32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, False, pid)
if hProcess:
exe_name = ctypes.create_unicode_buffer(260)
if psapi.GetModuleBaseNameW(hProcess, None, exe_name, 260):
result['process_name'] = exe_name.value.lower()
exe_path = ctypes.create_unicode_buffer(260)
if psapi.GetModuleFileNameExW(hProcess, None, exe_path, 260):
result['process_path'] = exe_path.value.lower()
kernel32.CloseHandle(hProcess)
else:
try:
process = psutil.Process(pid)
result['process_name'] = process.name().lower()
result['process_path'] = process.exe().lower() if process.exe() else ''
except:
pass
except Exception as e:
console_print(f"获取进程信息异常: {e}")
return result
# ==================== 项目信息元数据 ====================
class ProjectInfo:
"""项目信息元数据(集中管理所有项目相关信息)"""
VERSION = "1.2.0"
BUILD_DATE = "2026-03-26"
AUTHOR = "杜玛"
LICENSE = "GNU Affero General Public License v3.0"
COPYRIGHT = "© 永久 杜玛"
URL = "https://github.com/duma520/KeyForge"
MAINTAINER_EMAIL = "不提供"
NAME = "KeyForge 后台按键测试工具"
DESCRIPTION = "KeyForge 后台按键测试工具,支持多种按键发送方式、多种窗口枚举方式,并提供丰富的调试信息输出。"
@classmethod
def get_full_name(cls) -> str:
return f"{cls.NAME} v{cls.VERSION}"
@classmethod
def get_full_title(cls, username: str = None) -> str:
base = f"{cls.get_full_name()} 构建:{cls.BUILD_DATE}"
if username:
return f"{base} - 当前用户: {username}"
return base
@classmethod
def get_about_text(cls) -> str:
return f"""
<h2>{cls.NAME}</h2>
<p><b>版本:</b> {cls.VERSION}</p>
<p><b>构建日期:</b> {cls.BUILD_DATE}</p>
<p><b>作者:</b> {cls.AUTHOR}</p>
<p><b>版权:</b> {cls.COPYRIGHT}</p>
<p><b>许可证:</b> {cls.LICENSE}</p>
<p><b>项目主页:</b> <a href='{cls.URL}'>{cls.URL}</a></p>
<p><b>描述:</b> {cls.DESCRIPTION}</p>
<p><b>支持按键方式:</b> {BackendKeyMethod.get_total_count()} 种</p>
"""
# 增强的按键发送类
class EnhancedKeyPressThread(QThread):
progress_updated = Signal(int)
status_updated = Signal(str)
log_message = Signal(str)
loop_count_updated = Signal(int)
def __init__(self):
super().__init__()
self.running = False
self.selected_windows = []
self.key_type = "A"
self.method = BackendKeyMethod.SENDMESSAGE
self.delay = 1.0
self.repeat_count = 1
self.modifiers = []
self.param_lock = threading.Lock()
self.current_loop = 0
self.total_windows = 0
def update_parameters(self, key_type, method, delay, repeat_count, modifiers=None):
"""动态更新参数"""
with self.param_lock:
self.key_type = key_type
self.method = method
self.delay = delay
self.repeat_count = repeat_count
if modifiers is not None:
self.modifiers = modifiers
def get_parameters(self):
"""获取当前参数"""
with self.param_lock:
return self.key_type, self.method, self.delay, self.repeat_count, self.modifiers
def get_vk_code(self, key_type):
"""获取虚拟键码"""
if key_type.startswith("0x") or key_type.startswith("0X"):
try:
return int(key_type, 16)
except:
pass
elif key_type.isdigit():
try:
return int(key_type)
except:
pass
return KEY_MAP.get(key_type, 0x41)
def get_modifier_codes(self, modifiers):
"""获取组合键的虚拟键码列表"""
codes = []
for mod in modifiers:
if mod in MODIFIER_KEYS:
codes.append(MODIFIER_KEYS[mod])
return codes
def get_modifier_flags(self):
"""获取组合键的MOD_标志"""
flags = 0
if "Alt" in self.modifiers:
flags |= 0x0001
if "Ctrl" in self.modifiers:
flags |= 0x0002
if "Shift" in self.modifiers:
flags |= 0x0004
if "Win" in self.modifiers:
flags |= 0x0008
return flags
def send_keybd_event(self, vk_code, is_down):
"""使用keybd_event发送按键"""
flags_val = 0 if is_down else win32con.KEYEVENTF_KEYUP
ctypes.windll.user32.keybd_event(vk_code, 0, flags_val, 0)
def send_sendinput(self, vk_code, is_down):
"""使用SendInput发送按键"""
INPUT_KEYBOARD = 1
class KEYBDINPUT(ctypes.Structure):
_fields_ = [("wVk", ctypes.c_ushort),
("wScan", ctypes.c_ushort),
("dwFlags", ctypes.c_ulong),
("time", ctypes.c_ulong),
("dwExtraInfo", ctypes.c_ulong)]
class INPUT(ctypes.Structure):
_fields_ = [("type", ctypes.c_ulong),
("ki", KEYBDINPUT)]
flags = 0 if is_down else win32con.KEYEVENTF_KEYUP
input_struct = INPUT()
input_struct.type = INPUT_KEYBOARD
input_struct.ki = KEYBDINPUT(vk_code, 0, flags, 0, 0)
ctypes.windll.user32.SendInput(1, ctypes.byref(input_struct), ctypes.sizeof(INPUT))
def send_attach_thread_input(self, hwnd, vk_code, is_down):
"""使用AttachThreadInput方式"""
try:
current_thread = win32api.GetCurrentThreadId()
target_thread = win32process.GetWindowThreadProcessId(hwnd)[0]
win32process.AttachThreadInput(current_thread, target_thread, True)
self.send_keybd_event(vk_code, is_down)
win32process.AttachThreadInput(current_thread, target_thread, False)
return True
except Exception as e:
self.log_message.emit(f"AttachThreadInput错误: {e}")
return False
def send_wm_hotkey(self, hwnd, vk_code, is_down):
"""使用WM_HOTKEY消息"""
if is_down:
hotkey_id = 1
try:
win32gui.RegisterHotKey(hwnd, hotkey_id, self.get_modifier_flags(), vk_code)
win32gui.PostMessage(hwnd, win32con.WM_HOTKEY, hotkey_id, 0)
win32gui.UnregisterHotKey(hwnd, hotkey_id)
except:
pass
return True
def send_wm_appcommand(self, hwnd, vk_code, is_down):
"""使用WM_APPCOMMAND消息"""
if is_down:
win32gui.PostMessage(hwnd, win32con.WM_APPCOMMAND, 0, vk_code << 16)
return True
def send_broadcast_msg(self, vk_code, is_down):
"""广播系统消息"""
if is_down:
win32gui.BroadcastSystemMessage(
win32con.BSF_IGNORECURRENTTASK | win32con.BSF_POSTMESSAGE,
0, win32con.WM_KEYDOWN, vk_code, 0)
return True
def send_scan_code(self, hwnd, vk_code, is_down):
"""扫描码方式"""
try:
scan_code = ctypes.windll.user32.MapVirtualKeyW(vk_code, 0)
lParam = (scan_code << 16) | (1 if is_down else 0xC0000000)
if is_down:
win32gui.PostMessage(hwnd, win32con.WM_KEYDOWN, vk_code, lParam)
else:
win32gui.PostMessage(hwnd, win32con.WM_KEYUP, vk_code, lParam)
return True
except Exception as e:
self.log_message.emit(f"扫描码方式错误: {e}")
return False
def send_extended_key(self, hwnd, vk_code, is_down):
"""扩展键标志方式"""
try:
scan_code = ctypes.windll.user32.MapVirtualKeyW(vk_code, 0)
extended = 1
lParam = (1 & 0xFFFF) | ((scan_code & 0xFF) << 16) | ((extended & 1) << 24)
if is_down:
win32gui.PostMessage(hwnd, win32con.WM_KEYDOWN, vk_code, lParam)
else:
lParam |= (1 << 30) | (1 << 31)
win32gui.PostMessage(hwnd, win32con.WM_KEYUP, vk_code, lParam)
return True
except Exception as e:
self.log_message.emit(f"扩展键标志错误: {e}")
return False
def send_wm_copydata(self, hwnd, vk_code, is_down):
"""使用WM_COPYDATA发送"""
if is_down:
class COPYDATASTRUCT(ctypes.Structure):
_fields_ = [
("dwData", ctypes.c_ulong),
("cbData", ctypes.c_ulong),
("lpData", ctypes.c_void_p)
]
data = struct.pack('I', vk_code)
cds = COPYDATASTRUCT()
cds.dwData = 0x4B455900
cds.cbData = len(data)
cds.lpData = ctypes.addressof(ctypes.create_string_buffer(data))
win32gui.SendMessage(hwnd, win32con.WM_COPYDATA, 0, cds)
return True
def send_clipboard(self, key_type):
"""通过剪贴板发送文本"""
try:
import win32clipboard
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardText(key_type)
win32clipboard.CloseClipboard()
for hwnd in self.selected_windows:
win32gui.PostMessage(hwnd, win32con.WM_KEYDOWN, 0x11, 0)
time.sleep(0.02)
win32gui.PostMessage(hwnd, win32con.WM_KEYDOWN, 0x56, 0)
time.sleep(0.02)
win32gui.PostMessage(hwnd, win32con.WM_KEYUP, 0x56, 0)
time.sleep(0.02)
win32gui.PostMessage(hwnd, win32con.WM_KEYUP, 0x11, 0)
return True
except Exception as e:
self.log_message.emit(f"剪贴板方式错误: {e}")
return False
def send_com_object(self, vk_code, is_down):
"""COM对象调用"""
try:
import win32com.client
shell = win32com.client.Dispatch("WScript.Shell")
if is_down:
if 32 <= vk_code <= 126:
shell.SendKeys(chr(vk_code))
else:
shell.SendKeys('{' + self.key_type.upper() + '}')
return True
except Exception as e:
self.log_message.emit(f"COM对象错误: {e}")
return False
# ==================== 不带组合键的发送方法 ====================
def send_key_without_modifiers(self, hwnd, vk_code, method, char_code=0):
"""发送不带组合键的按键"""
try:
if method == BackendKeyMethod.SENDMESSAGE:
win32gui.SendMessage(hwnd, win32con.WM_KEYDOWN, vk_code, 0)
time.sleep(0.02)
win32gui.SendMessage(hwnd, win32con.WM_KEYUP, vk_code, 0)
return True
elif method == BackendKeyMethod.POSTMESSAGE:
win32gui.PostMessage(hwnd, win32con.WM_KEYDOWN, vk_code, 0)
time.sleep(0.02)
win32gui.PostMessage(hwnd, win32con.WM_KEYUP, vk_code, 0)
return True
elif method == BackendKeyMethod.KEYBD_EVENT:
self.send_keybd_event(vk_code, True)
time.sleep(0.02)
self.send_keybd_event(vk_code, False)
return True
elif method == BackendKeyMethod.SENDINPUT:
self.send_sendinput(vk_code, True)
time.sleep(0.02)
self.send_sendinput(vk_code, False)
return True
elif method == BackendKeyMethod.WM_KEYDOWN_DIRECT:
lParam = (1 << 30) | (1 << 31) | (1 << 29)
win32gui.PostMessage(hwnd, win32con.WM_KEYDOWN, vk_code, lParam)
time.sleep(0.02)
win32gui.PostMessage(hwnd, win32con.WM_KEYUP, vk_code, lParam)
return True
elif method == BackendKeyMethod.WM_CHAR:
if char_code:
win32gui.PostMessage(hwnd, win32con.WM_CHAR, char_code, 0)
return True
else:
win32gui.PostMessage(hwnd, win32con.WM_KEYDOWN, vk_code, 0)
time.sleep(0.02)
win32gui.PostMessage(hwnd, win32con.WM_KEYUP, vk_code, 0)
return True
elif method == BackendKeyMethod.WM_IME_CHAR:
if char_code:
win32gui.PostMessage(hwnd, win32con.WM_IME_CHAR, char_code, 0)
else:
win32gui.PostMessage(hwnd, win32con.WM_IME_CHAR, vk_code, 0)
return True
elif method == BackendKeyMethod.WM_SYSKEYDOWN:
win32gui.PostMessage(hwnd, win32con.WM_SYSKEYDOWN, vk_code, 0)
time.sleep(0.02)
win32gui.PostMessage(hwnd, win32con.WM_SYSKEYUP, vk_code, 0)
return True
elif method == BackendKeyMethod.POSTMESSAGE_LPARAM:
def make_lparam(repeat, scan, extended, context, previous):
return (repeat & 0xFFFF) | ((scan & 0xFF) << 16) | \
((extended & 1) << 24) | ((context & 1) << 29) | \
((previous & 1) << 30)
lParam = make_lparam(1, 0, 0, 0, 0)
win32gui.PostMessage(hwnd, win32con.WM_KEYDOWN, vk_code, lParam)
time.sleep(0.02)
lParam_up = make_lparam(1, 0, 0, 1, 1)
win32gui.PostMessage(hwnd, win32con.WM_KEYUP, vk_code, lParam_up)
return True
elif method == BackendKeyMethod.WM_HOTKEY:
return self.send_wm_hotkey(hwnd, vk_code, True)
elif method == BackendKeyMethod.WM_APPCOMMAND:
return self.send_wm_appcommand(hwnd, vk_code, True)
elif method == BackendKeyMethod.SENDMESSAGE_TIMEOUT:
ctypes.windll.user32.SendMessageTimeoutW(
hwnd, win32con.WM_KEYDOWN, vk_code, 0, 0x0002, 1000, None)
time.sleep(0.02)
ctypes.windll.user32.SendMessageTimeoutW(
hwnd, win32con.WM_KEYUP, vk_code, 0, 0x0002, 1000, None)
return True
elif method == BackendKeyMethod.BROADCAST_MSG:
return self.send_broadcast_msg(vk_code, True) and \
self.send_broadcast_msg(vk_code, False)
elif method == BackendKeyMethod.ATTACH_THREAD:
return self.send_attach_thread_input(hwnd, vk_code, True) and \
self.send_attach_thread_input(hwnd, vk_code, False)
elif method == BackendKeyMethod.SCAN_CODE:
return self.send_scan_code(hwnd, vk_code, True) and \
self.send_scan_code(hwnd, vk_code, False)
elif method == BackendKeyMethod.EXTENDED_KEY:
return self.send_extended_key(hwnd, vk_code, True) and \
self.send_extended_key(hwnd, vk_code, False)
elif method == BackendKeyMethod.WM_COPYDATA:
return self.send_wm_copydata(hwnd, vk_code, True)
elif method == BackendKeyMethod.CLIPBOARD:
return self.send_clipboard(chr(vk_code) if 32 <= vk_code <= 126 else str(vk_code))
elif method == BackendKeyMethod.COM_OBJECT:
return self.send_com_object(vk_code, True) and \
self.send_com_object(vk_code, False)
else:
win32gui.PostMessage(hwnd, win32con.WM_KEYDOWN, vk_code, 0)
time.sleep(0.02)
win32gui.PostMessage(hwnd, win32con.WM_KEYUP, vk_code, 0)
return True
except Exception as e:
self.log_message.emit(f"错误: {str(e)}")
return False
# ==================== 带组合键的发送方法 ====================
def send_key_with_modifiers(self, hwnd, vk_code, method, char_code=0):
"""发送带组合键的按键"""
try:
modifier_codes = self.get_modifier_codes(self.modifiers)
if not modifier_codes:
return self.send_key_without_modifiers(hwnd, vk_code, method, char_code)
# 全局输入模拟方法
if method in [BackendKeyMethod.KEYBD_EVENT, BackendKeyMethod.SENDINPUT]:
for mod_code in modifier_codes:
self.send_keybd_event(mod_code, True)
time.sleep(0.005)
self.send_keybd_event(vk_code, True)
time.sleep(0.02)
self.send_keybd_event(vk_code, False)
time.sleep(0.005)
for mod_code in reversed(modifier_codes):
self.send_keybd_event(mod_code, False)
time.sleep(0.005)
return True
# 窗口消息发送方法
elif method in [BackendKeyMethod.SENDMESSAGE, BackendKeyMethod.POSTMESSAGE,
BackendKeyMethod.WM_KEYDOWN_DIRECT, BackendKeyMethod.POSTMESSAGE_LPARAM,
BackendKeyMethod.WM_SYSKEYDOWN, BackendKeyMethod.SENDMESSAGE_TIMEOUT]:
def make_lparam(repeat, scan, extended, context, previous):
return (repeat & 0xFFFF) | ((scan & 0xFF) << 16) | \
((extended & 1) << 24) | ((context & 1) << 29) | \
((previous & 1) << 30)
for mod_code in modifier_codes:
if method == BackendKeyMethod.SENDMESSAGE:
win32gui.SendMessage(hwnd, win32con.WM_KEYDOWN, mod_code, 0)
elif method == BackendKeyMethod.SENDMESSAGE_TIMEOUT:
ctypes.windll.user32.SendMessageTimeoutW(
hwnd, win32con.WM_KEYDOWN, mod_code, 0, 0x0002, 1000, None)
else:
win32gui.PostMessage(hwnd, win32con.WM_KEYDOWN, mod_code, 0)
time.sleep(0.005)
if method == BackendKeyMethod.SENDMESSAGE:
win32gui.SendMessage(hwnd, win32con.WM_KEYDOWN, vk_code, 0)
time.sleep(0.02)
win32gui.SendMessage(hwnd, win32con.WM_KEYUP, vk_code, 0)
elif method == BackendKeyMethod.SENDMESSAGE_TIMEOUT:
ctypes.windll.user32.SendMessageTimeoutW(
hwnd, win32con.WM_KEYDOWN, vk_code, 0, 0x0002, 1000, None)
time.sleep(0.02)
ctypes.windll.user32.SendMessageTimeoutW(
hwnd, win32con.WM_KEYUP, vk_code, 0, 0x0002, 1000, None)
elif method == BackendKeyMethod.BROADCAST_MSG:
win32gui.BroadcastSystemMessage(
win32con.BSF_IGNORECURRENTTASK | win32con.BSF_POSTMESSAGE,
0, win32con.WM_KEYDOWN, vk_code, 0)
time.sleep(0.02)
win32gui.BroadcastSystemMessage(
win32con.BSF_IGNORECURRENTTASK | win32con.BSF_POSTMESSAGE,
0, win32con.WM_KEYUP, vk_code, 0)
else:
lParam = make_lparam(1, 0, 0, 0, 0)
win32gui.PostMessage(hwnd, win32con.WM_KEYDOWN, vk_code, lParam)
time.sleep(0.02)
lParam_up = make_lparam(1, 0, 0, 1, 1)
win32gui.PostMessage(hwnd, win32con.WM_KEYUP, vk_code, lParam_up)
time.sleep(0.005)
for mod_code in reversed(modifier_codes):
if method == BackendKeyMethod.SENDMESSAGE:
win32gui.SendMessage(hwnd, win32con.WM_KEYUP, mod_code, 0)
elif method == BackendKeyMethod.SENDMESSAGE_TIMEOUT:
ctypes.windll.user32.SendMessageTimeoutW(
hwnd, win32con.WM_KEYUP, mod_code, 0, 0x0002, 1000, None)
else:
win32gui.PostMessage(hwnd, win32con.WM_KEYUP, mod_code, 0)
time.sleep(0.005)
return True
# 扫描码/扩展键方式
elif method in [BackendKeyMethod.SCAN_CODE, BackendKeyMethod.EXTENDED_KEY]:
scan_code = ctypes.windll.user32.MapVirtualKeyW(vk_code, 0)
extended = 1 if method == BackendKeyMethod.EXTENDED_KEY else 0
def make_lparam_scan(repeat, scan, extended, context, previous):
return (repeat & 0xFFFF) | ((scan & 0xFF) << 16) | \
((extended & 1) << 24) | ((context & 1) << 29) | \
((previous & 1) << 30)
for mod_code in modifier_codes:
mod_scan = ctypes.windll.user32.MapVirtualKeyW(mod_code, 0)
lParam_mod = make_lparam_scan(1, mod_scan, 0, 0, 0)
win32gui.PostMessage(hwnd, win32con.WM_KEYDOWN, mod_code, lParam_mod)
time.sleep(0.005)
lParam = make_lparam_scan(1, scan_code, extended, 0, 0)
win32gui.PostMessage(hwnd, win32con.WM_KEYDOWN, vk_code, lParam)
time.sleep(0.02)
lParam_up = make_lparam_scan(1, scan_code, extended, 1, 1)
win32gui.PostMessage(hwnd, win32con.WM_KEYUP, vk_code, lParam_up)
time.sleep(0.005)
for mod_code in reversed(modifier_codes):
mod_scan = ctypes.windll.user32.MapVirtualKeyW(mod_code, 0)
lParam_mod_up = make_lparam_scan(1, mod_scan, 0, 1, 1)
win32gui.PostMessage(hwnd, win32con.WM_KEYUP, mod_code, lParam_mod_up)
time.sleep(0.005)
return True
# 线程附加方式
elif method == BackendKeyMethod.ATTACH_THREAD:
try:
current_thread = win32api.GetCurrentThreadId()
target_thread = win32process.GetWindowThreadProcessId(hwnd)[0]
win32process.AttachThreadInput(current_thread, target_thread, True)
old_focus = win32gui.GetFocus()
win32gui.SetFocus(hwnd)
for mod_code in modifier_codes:
self.send_keybd_event(mod_code, True)
time.sleep(0.005)
self.send_keybd_event(vk_code, True)
time.sleep(0.02)
self.send_keybd_event(vk_code, False)
time.sleep(0.005)
for mod_code in reversed(modifier_codes):
self.send_keybd_event(mod_code, False)
time.sleep(0.005)
if old_focus:
win32gui.SetFocus(old_focus)
win32process.AttachThreadInput(current_thread, target_thread, False)
return True
except Exception as e:
self.log_message.emit(f"线程附加方式错误: {e}")
return False
# 字符消息方式
elif method == BackendKeyMethod.WM_CHAR:
if char_code:
win32gui.PostMessage(hwnd, win32con.WM_CHAR, char_code, 0)
return True
else:
return self.send_key_with_modifiers(hwnd, vk_code, BackendKeyMethod.POSTMESSAGE, char_code)
elif method == BackendKeyMethod.WM_IME_CHAR:
if char_code:
win32gui.PostMessage(hwnd, win32con.WM_IME_CHAR, char_code, 0)
else:
win32gui.PostMessage(hwnd, win32con.WM_IME_CHAR, vk_code, 0)
return True
# 热键方式
elif method == BackendKeyMethod.WM_HOTKEY:
hotkey_id = 1
try:
win32gui.RegisterHotKey(hwnd, hotkey_id, self.get_modifier_flags(), vk_code)
win32gui.PostMessage(hwnd, win32con.WM_HOTKEY, hotkey_id, 0)
win32gui.UnregisterHotKey(hwnd, hotkey_id)
return True
except:
return self.send_key_with_modifiers(hwnd, vk_code, BackendKeyMethod.POSTMESSAGE, char_code)
# COM对象方式
elif method == BackendKeyMethod.COM_OBJECT:
try:
import win32com.client
shell = win32com.client.Dispatch("WScript.Shell")
modifier_map = {"Ctrl": "^", "Alt": "%", "Shift": "+", "Win": "#"}
key_str = ""
for mod in self.modifiers:
if mod in modifier_map:
key_str += modifier_map[mod]
if 32 <= vk_code <= 126:
key_str += chr(vk_code)
else:
key_str += "{" + self.key_type.upper() + "}"
shell.SendKeys(key_str)
return True
except Exception as e:
self.log_message.emit(f"COM对象方式错误: {e}")
return False
else:
return self.send_key_with_modifiers(hwnd, vk_code, BackendKeyMethod.POSTMESSAGE, char_code)
except Exception as e:
self.log_message.emit(f"组合键发送错误: {str(e)}")
return False
# ==================== 主发送方法 ====================
def send_key_to_window_advanced(self, hwnd, key_type, method):
"""增强的按键发送方法(支持组合键)"""
vk_code = self.get_vk_code(key_type)
char_code = 0
if len(key_type) == 1:
char_code = ord(key_type[0])
has_modifiers = len(self.modifiers) > 0
modifier_str = ""
if has_modifiers:
modifier_str = " + ".join(self.modifiers) + " + "
if has_modifiers:
success = self.send_key_with_modifiers(hwnd, vk_code, method, char_code)
if success:
self.log_message.emit(f"{BackendKeyMethod.get_method_name(method)}: 已发送组合键 [{modifier_str}{key_type}]")
else:
success = self.send_key_without_modifiers(hwnd, vk_code, method, char_code)
if success:
self.log_message.emit(f"{BackendKeyMethod.get_method_name(method)}: 已发送 {key_type} 键")
return success
def run(self):
self.running = True
key_type, method, delay, repeat_count, modifiers = self.get_parameters()
is_infinite = (repeat_count == 0)
self.total_windows = len(self.selected_windows)
if is_infinite:
total_operations = 0
else:
total_operations = self.total_windows * repeat_count
current_operation = 0
self.current_loop = 0
while self.running:
if not is_infinite and self.current_loop >= repeat_count:
break
key_type, method, delay, repeat_count, modifiers = self.get_parameters()
is_infinite = (repeat_count == 0)
for idx, hwnd in enumerate(self.selected_windows):
if not self.running:
break
success = self.send_key_to_window_advanced(hwnd, key_type, method)
if not is_infinite:
current_operation += 1
progress_percent = int(current_operation / total_operations * 100)
self.progress_updated.emit(progress_percent)
if success:
modifier_str = " + ".join(modifiers) + " + " if modifiers else ""
self.status_updated.emit(f"成功发送 {modifier_str}{key_type} 到窗口 {idx+1}/{self.total_windows} (第{self.current_loop+1}轮)")
else:
self.status_updated.emit(f"发送失败到窗口 {idx+1}/{self.total_windows}")
time.sleep(delay)
self.current_loop += 1
if is_infinite:
self.status_updated.emit(f"已完成 {self.current_loop} 轮发送,继续循环...")
self.log_message.emit(f"已完成第 {self.current_loop} 轮发送(无限模式)")
self.progress_updated.emit(self.current_loop)
self.loop_count_updated.emit(self.current_loop)
if not self.running:
self.status_updated.emit("按键发送已停止")
else:
self.status_updated.emit("按键发送完成")
def stop(self):
self.running = False
# 增强的窗口枚举线程
class EnhancedWindowEnumThread(QThread):
windows_found = Signal(list)
progress_updated = Signal(int)
debug_log = Signal(str)
def __init__(self, enum_method, title_keyword, process_keyword, show_debug=False):
super().__init__()
self.enum_method = enum_method
self.title_keyword = title_keyword.lower() if title_keyword else ""
self.process_keyword = process_keyword.lower() if process_keyword else ""
self.show_debug = show_debug
def debug_print(self, message):
if self.show_debug:
self.debug_log.emit(message)
def run(self):
windows = []
total_visible = 0
matched_count = 0
def enum_callback(hwnd, extra):
nonlocal total_visible, matched_count
if win32gui.IsWindowVisible(hwnd):
total_visible += 1
window_text = win32gui.GetWindowText(hwnd)
if not window_text:
return True
class_name = win32gui.GetClassName(hwnd)
rect = win32gui.GetWindowRect(hwnd)
pid = win32process.GetWindowThreadProcessId(hwnd)[0]
process_info = get_all_process_names_from_hwnd(hwnd)
process_name = process_info['process_name']
process_path = process_info['process_path']
if self.show_debug and total_visible <= 100:
debug_info = f"窗口: '{window_text[:40]}' | 类名: '{class_name}' | PID:{pid} | 进程: '{process_name}'"
self.debug_print(debug_info)
matched = False
if self.enum_method == EnumMethod.BY_TITLE:
if self.title_keyword and self.title_keyword in window_text.lower():
matched = True
elif self.enum_method == EnumMethod.BY_PROCESS:
if self.process_keyword:
if self.process_keyword in process_name:
matched = True
elif process_path and self.process_keyword in os.path.basename(process_path).lower():
matched = True
elif self.process_keyword in class_name.lower():
matched = True
elif self.enum_method == EnumMethod.BY_BOTH:
title_match = self.title_keyword and self.title_keyword in window_text.lower()
process_match = False
if self.process_keyword:
if (self.process_keyword in process_name or
(process_path and self.process_keyword in os.path.basename(process_path).lower()) or
self.process_keyword in class_name.lower()):
process_match = True
if title_match and process_match:
matched = True
if matched:
matched_count += 1
windows.append({
'hwnd': hwnd,
'title': window_text,
'class': class_name,
'rect': rect,