-
Notifications
You must be signed in to change notification settings - Fork 160
/
Copy pathchrome_manager.py
1752 lines (1455 loc) · 75.2 KB
/
chrome_manager.py
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 tkinter as tk
from tkinter import ttk, messagebox
import os
import subprocess
import win32gui
import win32process
import win32con
import win32api
import win32com.client
import json
from typing import List, Dict, Optional
import math
import ctypes
from ctypes import wintypes
import threading
import time
import sys
import keyboard
import mouse
import webbrowser
import sv_ttk
def is_admin():
# 检查是否具有管理员权限
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
return False
def run_as_admin():
# 以管理员权限重新运行程序
ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1)
class ChromeManager:
def __init__(self):
if not is_admin():
if messagebox.askyesno("权限不足", "需要管理员权限才能运行同步功能。\n是否以管理员身份重新启动程序?"):
run_as_admin()
sys.exit()
self.root = tk.Tk()
self.root.title("NoBiggie社区Chrome多窗口管理器 V1.0")
try:
icon_path = os.path.join(os.path.dirname(__file__), "app.ico")
if os.path.exists(icon_path):
self.root.iconbitmap(icon_path)
except Exception as e:
print(f"设置图标失败: {str(e)}")
last_position = self.load_window_position()
if last_position:
self.root.geometry(last_position)
sv_ttk.set_theme("light") # 使用 light 主题
self.window_list = None # 先初始化为 None
self.windows = []
self.master_window = None
self.shortcut_path = self.load_settings().get('shortcut_path', '')
self.shell = win32com.client.Dispatch("WScript.Shell")
self.select_all_var = tk.StringVar(value="全部选择")
self.is_syncing = False
self.sync_button = None
self.mouse_hook_id = None
self.keyboard_hook = None
self.hook_thread = None
self.user32 = ctypes.WinDLL('user32', use_last_error=True)
self.sync_windows = []
self.chrome_drivers = {}
self.debug_ports = {}
self.base_debug_port = 9222
self.DWMWA_BORDER_COLOR = 34
self.DWM_MAGIC_COLOR = 0x00FF0000
self.popup_mappings = {}
self.popup_monitor_thread = None
self.mouse_threshold = 3
self.last_mouse_position = (0, 0)
self.last_move_time = 0
self.move_interval = 0.016
self.shortcut_hook = None
self.current_shortcut = None
# 从设置中加载快捷键
settings = self.load_settings()
if 'sync_shortcut' in settings:
self.set_shortcut(settings['sync_shortcut'])
self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
# 创建界面
self.create_widgets()
self.create_styles()
self.root.update()
current_width = self.root.winfo_width()
current_height = self.root.winfo_height()
self.root.geometry(f"{current_width}x{current_height}")
self.root.resizable(False, False)
def create_styles(self):
style = ttk.Style()
default_font = ('Microsoft YaHei UI', 9)
style.configure('Small.TEntry',
padding=(4, 0),
font=default_font
)
style.configure('TButton', font=default_font)
style.configure('TLabel', font=default_font)
style.configure('TEntry', font=default_font)
style.configure('Treeview', font=default_font)
style.configure('Treeview.Heading', font=default_font)
style.configure('TLabelframe.Label', font=default_font)
style.configure('TNotebook.Tab', font=default_font)
if self.window_list:
self.window_list.tag_configure("master",
background="#0d6efd",
foreground='white'
)
# 链接样式
style.configure('Link.TLabel',
foreground='#0d6efd',
cursor='hand2',
font=('Microsoft YaHei UI', 9, 'underline')
)
def create_widgets(self):
# 创建界面元素
main_frame = ttk.Frame(self.root)
main_frame.pack(fill=tk.X, padx=10, pady=5)
upper_frame = ttk.Frame(main_frame)
upper_frame.pack(fill=tk.X)
arrange_frame = ttk.LabelFrame(upper_frame, text="自定义排列")
arrange_frame.pack(side=tk.RIGHT, fill=tk.Y, padx=(3, 0))
manage_frame = ttk.LabelFrame(upper_frame, text="窗口管理")
manage_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=(0, 5))
button_frame = ttk.Frame(manage_frame)
button_frame.pack(fill=tk.X)
ttk.Button(button_frame, text="导入窗口", command=self.import_windows, style='Accent.TButton').pack(side=tk.LEFT, padx=2)
select_all_label = ttk.Label(button_frame, textvariable=self.select_all_var, style='Link.TLabel')
select_all_label.pack(side=tk.LEFT, padx=5)
select_all_label.bind('<Button-1>', self.toggle_select_all)
ttk.Button(button_frame, text="自动排列", command=self.auto_arrange_windows).pack(side=tk.LEFT, padx=2)
ttk.Button(button_frame, text="关闭选中", command=self.close_selected_windows).pack(side=tk.LEFT, padx=2)
self.sync_button = ttk.Button(
button_frame,
text="▶ 开始同步",
command=self.toggle_sync,
style='Accent.TButton'
)
self.sync_button.pack(side=tk.LEFT, padx=5)
ttk.Button(
button_frame,
text="快捷键",
command=self.show_shortcut_dialog,
style='Accent.TButton'
).pack(side=tk.LEFT, padx=5)
# 在 button_frame 中添加屏幕选择下拉框
screen_frame = ttk.Frame(button_frame)
screen_frame.pack(side=tk.LEFT, padx=2)
ttk.Label(screen_frame, text="屏幕:").pack(side=tk.LEFT)
# 创建屏幕选择下拉框
self.screen_var = tk.StringVar()
self.screen_combo = ttk.Combobox(
screen_frame,
textvariable=self.screen_var,
width=8,
state="readonly"
)
self.screen_combo.pack(side=tk.LEFT)
# 获取并设置屏幕列表
self.update_screen_list()
list_frame = ttk.Frame(manage_frame)
list_frame.pack(fill=tk.BOTH, expand=True, pady=2)
# 创建窗口列表
self.window_list = ttk.Treeview(list_frame,
columns=("select", "number", "title", "master", "hwnd"),
show="headings",
height=4,
style='Accent.Treeview'
)
self.window_list.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
self.window_list.heading("select", text="选择")
self.window_list.heading("number", text="序号")
self.window_list.heading("title", text="标题")
self.window_list.heading("master", text="主控")
self.window_list.heading("hwnd", text="")
self.window_list.column("select", width=40, anchor="center")
self.window_list.column("number", width=40, anchor="center")
self.window_list.column("title", width=300)
self.window_list.column("master", width=40, anchor="center")
self.window_list.column("hwnd", width=0, stretch=False) # 隐藏hwnd列
self.window_list.tag_configure("master", background="lightblue")
self.window_list.bind('<Button-1>', self.on_click)
# 添加滚动条
scrollbar = ttk.Scrollbar(list_frame, orient=tk.VERTICAL, command=self.window_list.yview)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
self.window_list.configure(yscrollcommand=scrollbar.set)
params_frame = ttk.Frame(arrange_frame)
params_frame.pack(fill=tk.X, padx=5, pady=2)
left_frame = ttk.Frame(params_frame)
left_frame.pack(side=tk.LEFT, padx=(0, 5))
right_frame = ttk.Frame(params_frame)
right_frame.pack(side=tk.LEFT)
ttk.Label(left_frame, text="起始X坐标").pack(anchor=tk.W)
self.start_x = ttk.Entry(left_frame, width=8, style='Small.TEntry')
self.start_x.pack(fill=tk.X, pady=(0, 2))
self.start_x.insert(0, "0")
ttk.Label(left_frame, text="窗口宽度").pack(anchor=tk.W)
self.window_width = ttk.Entry(left_frame, width=8, style='Small.TEntry')
self.window_width.pack(fill=tk.X, pady=(0, 2))
self.window_width.insert(0, "500")
ttk.Label(left_frame, text="水平间距").pack(anchor=tk.W)
self.h_spacing = ttk.Entry(left_frame, width=8, style='Small.TEntry')
self.h_spacing.pack(fill=tk.X, pady=(0, 2))
self.h_spacing.insert(0, "0")
ttk.Label(right_frame, text="起始Y坐标").pack(anchor=tk.W)
self.start_y = ttk.Entry(right_frame, width=8, style='Small.TEntry')
self.start_y.pack(fill=tk.X, pady=(0, 2))
self.start_y.insert(0, "0")
ttk.Label(right_frame, text="窗口高度").pack(anchor=tk.W)
self.window_height = ttk.Entry(right_frame, width=8, style='Small.TEntry')
self.window_height.pack(fill=tk.X, pady=(0, 2))
self.window_height.insert(0, "400")
ttk.Label(right_frame, text="垂直间距").pack(anchor=tk.W)
self.v_spacing = ttk.Entry(right_frame, width=8, style='Small.TEntry')
self.v_spacing.pack(fill=tk.X, pady=(0, 2))
self.v_spacing.insert(0, "0")
for widget in left_frame.winfo_children() + right_frame.winfo_children():
if isinstance(widget, ttk.Entry):
widget.pack_configure(pady=(0, 2))
bottom_frame = ttk.Frame(arrange_frame)
bottom_frame.pack(fill=tk.X, padx=5, pady=2)
row_frame = ttk.Frame(bottom_frame)
row_frame.pack(side=tk.LEFT)
ttk.Label(row_frame, text="每行窗口数").pack(anchor=tk.W)
self.windows_per_row = ttk.Entry(row_frame, width=8, style='Small.TEntry')
self.windows_per_row.pack(pady=(2, 0))
self.windows_per_row.insert(0, "5")
ttk.Button(bottom_frame, text="自定义排列",
command=self.custom_arrange_windows,
style='Accent.TButton'
).pack(side=tk.RIGHT, pady=(15, 0))
bottom_frame = ttk.Frame(self.root)
bottom_frame.pack(fill=tk.X, padx=10, pady=(5, 0))
self.tab_control = ttk.Notebook(bottom_frame)
self.tab_control.pack(side=tk.LEFT, fill=tk.X, expand=True)
open_window_tab = ttk.Frame(self.tab_control)
self.tab_control.add(open_window_tab, text="打开窗口")
input_frame = ttk.Frame(open_window_tab)
input_frame.pack(fill=tk.X, padx=5, pady=5)
ttk.Label(input_frame, text="快捷方式目录:").pack(side=tk.LEFT)
self.path_entry = ttk.Entry(input_frame)
self.path_entry.pack(side=tk.LEFT, fill=tk.X, expand=True)
self.path_entry.insert(0, self.shortcut_path)
numbers_frame = ttk.Frame(input_frame)
numbers_frame.pack(pady=5, padx=10, fill=tk.X)
ttk.Label(numbers_frame, text="窗口编号:").pack(side=tk.LEFT)
self.numbers_entry = ttk.Entry(numbers_frame)
self.numbers_entry.pack(side=tk.LEFT, padx=5, fill=tk.X, expand=True)
settings = self.load_settings()
if 'last_window_numbers' in settings:
self.numbers_entry.insert(0, settings['last_window_numbers'])
self.numbers_entry.bind('<Return>', lambda e: self.open_windows())
ttk.Button(
numbers_frame,
text="打开窗口",
command=self.open_windows
).pack(side=tk.LEFT)
url_tab = ttk.Frame(self.tab_control)
self.tab_control.add(url_tab, text="批量打开网页")
url_frame = ttk.Frame(url_tab)
url_frame.pack(fill=tk.X, padx=5, pady=5)
ttk.Label(url_frame, text="网址:").pack(side=tk.LEFT)
self.url_entry = ttk.Entry(url_frame)
self.url_entry.pack(side=tk.LEFT, fill=tk.X, expand=True)
self.url_entry.insert(0, "www.google.com")
self.url_entry.bind('<Return>', lambda e: self.batch_open_urls())
ttk.Button(url_frame, text="批量打开", command=self.batch_open_urls).pack(side=tk.LEFT, padx=5)
icon_tab = ttk.Frame(self.tab_control)
self.tab_control.add(icon_tab, text="替换图标")
icon_frame = ttk.Frame(icon_tab)
icon_frame.pack(fill=tk.X, padx=5, pady=5)
ttk.Label(icon_frame, text="图标目录:").pack(side=tk.LEFT)
self.icon_path_entry = ttk.Entry(icon_frame)
self.icon_path_entry.pack(side=tk.LEFT, fill=tk.X, expand=True)
ttk.Label(icon_frame, text="窗口编号:").pack(side=tk.LEFT, padx=(10, 0))
self.icon_window_numbers = ttk.Entry(icon_frame, width=15)
self.icon_window_numbers.pack(side=tk.LEFT, padx=(0, 5))
ttk.Label(icon_frame, text="示例: 1-5,7,9-12").pack(side=tk.LEFT)
ttk.Button(icon_frame, text="替换图标", command=self.set_taskbar_icons).pack(side=tk.LEFT, padx=5)
footer_frame = ttk.Frame(self.root)
footer_frame.pack(side=tk.BOTTOM, fill=tk.X, padx=10, pady=5)
author_frame = ttk.Frame(footer_frame)
author_frame.pack(side=tk.RIGHT)
ttk.Label(author_frame, text="Compiled by Devilflasher").pack(side=tk.LEFT)
ttk.Label(author_frame, text=" ").pack(side=tk.LEFT)
twitter_label = ttk.Label(
author_frame,
text="Twitter",
cursor="hand2",
font=("Arial", 9)
)
twitter_label.pack(side=tk.LEFT)
twitter_label.bind("<Button-1>", lambda e: webbrowser.open("https://x.com/DevilflasherX"))
ttk.Label(author_frame, text=" ").pack(side=tk.LEFT)
telegram_label = ttk.Label(
author_frame,
text="Telegram",
cursor="hand2",
font=("Arial", 9)
)
telegram_label.pack(side=tk.LEFT)
telegram_label.bind("<Button-1>", lambda e: webbrowser.open("https://t.me/devilflasher0"))
def toggle_select_all(self, event=None):
#切换全选状态
try:
items = self.window_list.get_children()
if not items:
return
current_text = self.select_all_var.get()
if current_text == "全部选择":
for item in items:
self.window_list.set(item, "select", "√")
else:
for item in items:
self.window_list.set(item, "select", "")
# 更新按钮状态
self.update_select_all_status()
except Exception as e:
print(f"切换全选状态失败: {str(e)}")
def update_select_all_status(self):
# 更新全选状态
try:
# 获取所有项目
items = self.window_list.get_children()
if not items:
self.select_all_var.set("全部选择")
return
# 检查是否全部选中
selected_count = sum(1 for item in items if self.window_list.set(item, "select") == "√")
# 根据选中数量设置按钮文本
if selected_count == len(items):
self.select_all_var.set("取消全选")
else:
self.select_all_var.set("全部选择")
except Exception as e:
print(f"更新全选状态失败: {str(e)}")
def on_click(self, event):
# 处理点击事件
try:
region = self.window_list.identify_region(event.x, event.y)
if region == "cell":
column = self.window_list.identify_column(event.x)
item = self.window_list.identify_row(event.y)
if column == "#1": # 选择列
current = self.window_list.set(item, "select")
self.window_list.set(item, "select", "" if current == "√" else "√")
# 更新全选按钮状态
self.update_select_all_status()
elif column == "#4": # 主控列
self.set_master_window(item)
except Exception as e:
print(f"处理点击事件失败: {str(e)}")
def set_master_window(self, item):
# 设置主控窗口
if not item:
return
try:
# 清除其他窗口的主控状态和标题
for i in self.window_list.get_children():
values = self.window_list.item(i)['values']
if values and len(values) >= 5:
hwnd = int(values[4])
title = values[2]
if title.startswith("[主控]"):
new_title = title.replace("[主控]", "").strip()
win32gui.SetWindowText(hwnd, new_title)
# 恢复默认边框颜色
try:
ctypes.windll.dwmapi.DwmSetWindowAttribute(
hwnd,
self.DWMWA_BORDER_COLOR,
ctypes.byref(ctypes.c_int(0)),
ctypes.sizeof(ctypes.c_int)
)
except:
pass
self.window_list.set(i, "master", "")
self.window_list.item(i, tags=())
# 设置新的主控窗口
values = self.window_list.item(item)['values']
self.master_window = int(values[4])
# 设置主控标记和蓝色背景
self.window_list.set(item, "master", "√")
self.window_list.item(item, tags=("master",))
# 修改窗口标题和边框颜色
title = values[2]
if not title.startswith("[主控]"):
new_title = f"[主控] {title}"
win32gui.SetWindowText(self.master_window, new_title)
try:
# 设置红色边框
ctypes.windll.dwmapi.DwmSetWindowAttribute(
self.master_window,
self.DWMWA_BORDER_COLOR,
ctypes.byref(ctypes.c_int(0x000000FF)),
ctypes.sizeof(ctypes.c_int)
)
except:
pass
except Exception as e:
print(f"设置主控窗口失败: {str(e)}")
def toggle_sync(self, event=None):
# 切换同步状态
if not self.window_list.get_children():
messagebox.showinfo("提示", "请先导入窗口!")
return
# 获取选中的窗口
selected = []
for item in self.window_list.get_children():
if self.window_list.set(item, "select") == "√":
selected.append(item)
if not selected:
messagebox.showinfo("提示", "请选择要同步的窗口!")
return
# 检查主控窗口
master_items = [item for item in self.window_list.get_children()
if self.window_list.set(item, "master") == "√"]
if not master_items:
# 如果没有主控窗口,设置第一个选中的窗口为主控
self.set_master_window(selected[0])
# 切换同步状态
if not self.is_syncing:
try:
self.start_sync(selected)
self.sync_button.configure(text="■ 停止同步", style='Accent.TButton')
self.is_syncing = True
print("同步已开启")
except Exception as e:
print(f"开启同步失败: {str(e)}")
# 确保状态正确
self.is_syncing = False
self.sync_button.configure(text="▶ 开始同步", style='Accent.TButton')
# 重新显示错误消息
messagebox.showerror("错误", str(e))
else:
try:
self.stop_sync()
self.sync_button.configure(text="▶ 开始同步", style='Accent.TButton')
self.is_syncing = False
print("同步已停止")
except Exception as e:
print(f"停止同步失败: {str(e)}")
def start_sync(self, selected_items):
try:
# 确保主控窗口存在
if not self.master_window:
raise Exception("未设置主控窗口")
# 保存选中的窗口列表,并按编号排序
self.sync_windows = []
window_info = []
# 收集所有选中的窗口
for item in selected_items:
values = self.window_list.item(item)['values']
if values and len(values) >= 5:
number = int(values[1])
hwnd = int(values[4])
if hwnd != self.master_window: # 排除主控窗口
window_info.append((number, hwnd))
# 按编号排序
window_info.sort(key=lambda x: x[0])
# 保存所有同步窗口的句柄
self.sync_windows = [hwnd for _, hwnd in window_info]
# 启动键盘和鼠标钩子
if not self.hook_thread:
self.is_syncing = True
self.hook_thread = threading.Thread(target=self.message_loop)
self.hook_thread.daemon = True
self.hook_thread.start()
keyboard.hook(self.on_keyboard_event)
mouse.hook(self.on_mouse_event)
# 更新按钮状态
self.sync_button.configure(text="■ 停止同步", style='Accent.TButton')
# 启动插件窗口监控线程
self.popup_monitor_thread = threading.Thread(target=self.monitor_popups)
self.popup_monitor_thread.daemon = True
self.popup_monitor_thread.start()
print(f"已启动同步,主控窗口: {self.master_window}, 同步窗口: {self.sync_windows}")
except Exception as e:
self.stop_sync() # 确保清理资源
print(f"开启同步失败: {str(e)}")
raise e
def message_loop(self):
# 消息循环
while self.is_syncing:
time.sleep(0.001)
def on_mouse_event(self, event):
try:
if self.is_syncing:
current_window = win32gui.GetForegroundWindow()
# 检查是否是主控窗口或其插件窗口
is_master = current_window == self.master_window
master_popups = self.get_chrome_popups(self.master_window)
is_popup = current_window in master_popups
if is_master or is_popup:
# 对于移动事件进行优化
if isinstance(event, mouse.MoveEvent):
# 检查移动距离和时间间隔
current_time = time.time()
if current_time - self.last_move_time < self.move_interval:
return
dx = abs(event.x - self.last_mouse_position[0])
dy = abs(event.y - self.last_mouse_position[1])
if dx < self.mouse_threshold and dy < self.mouse_threshold:
return
self.last_mouse_position = (event.x, event.y)
self.last_move_time = current_time
# 获取鼠标位置
x, y = mouse.get_position()
# 获取当前窗口的相对坐标
current_rect = win32gui.GetWindowRect(current_window)
rel_x = (x - current_rect[0]) / (current_rect[2] - current_rect[0])
rel_y = (y - current_rect[1]) / (current_rect[3] - current_rect[1])
# 同步到其他窗口
for hwnd in self.sync_windows:
try:
# 确定目标窗口
if is_master:
target_hwnd = hwnd
else:
# 查找对应的扩展程序窗口
target_popups = self.get_chrome_popups(hwnd)
# 按照相对位置匹配
best_match = None
min_diff = float('inf')
for popup in target_popups:
popup_rect = win32gui.GetWindowRect(popup)
master_rect = win32gui.GetWindowRect(current_window)
# 计算相对位置差异
master_rel_x = master_rect[0] - win32gui.GetWindowRect(self.master_window)[0]
master_rel_y = master_rect[1] - win32gui.GetWindowRect(self.master_window)[1]
popup_rel_x = popup_rect[0] - win32gui.GetWindowRect(hwnd)[0]
popup_rel_y = popup_rect[1] - win32gui.GetWindowRect(hwnd)[1]
diff = abs(master_rel_x - popup_rel_x) + abs(master_rel_y - popup_rel_y)
if diff < min_diff:
min_diff = diff
best_match = popup
target_hwnd = best_match if best_match else hwnd
if not target_hwnd:
continue
# 获取目标窗口尺寸
target_rect = win32gui.GetWindowRect(target_hwnd)
# 计算目标坐标
client_x = int((target_rect[2] - target_rect[0]) * rel_x)
client_y = int((target_rect[3] - target_rect[1]) * rel_y)
lparam = win32api.MAKELONG(client_x, client_y)
# 处理滚轮事件
if isinstance(event, mouse.WheelEvent):
try:
wheel_delta = int(event.delta)
if keyboard.is_pressed('ctrl'):
if wheel_delta > 0:
win32gui.PostMessage(target_hwnd, win32con.WM_KEYDOWN, win32con.VK_CONTROL, 0)
win32gui.PostMessage(target_hwnd, win32con.WM_KEYDOWN, 0xBB, 0) # VK_OEM_PLUS
win32gui.PostMessage(target_hwnd, win32con.WM_KEYUP, 0xBB, 0)
win32gui.PostMessage(target_hwnd, win32con.WM_KEYUP, win32con.VK_CONTROL, 0)
else:
win32gui.PostMessage(target_hwnd, win32con.WM_KEYDOWN, win32con.VK_CONTROL, 0)
win32gui.PostMessage(target_hwnd, win32con.WM_KEYDOWN, win32con.VK_CONTROL, 0)
win32gui.PostMessage(target_hwnd, win32con.WM_KEYDOWN, 0xBD, 0) # VK_OEM_MINUS
win32gui.PostMessage(target_hwnd, win32con.WM_KEYUP, 0xBD, 0)
win32gui.PostMessage(target_hwnd, win32con.WM_KEYUP, win32con.VK_CONTROL, 0)
else:
vk_code = win32con.VK_UP if wheel_delta > 0 else win32con.VK_DOWN
vk_code = win32con.VK_UP if wheel_delta > 0 else win32con.VK_DOWN
repeat_count = min(abs(wheel_delta) * 3, 6)
for _ in range(repeat_count):
win32gui.PostMessage(target_hwnd, win32con.WM_KEYDOWN, vk_code, 0)
win32gui.PostMessage(target_hwnd, win32con.WM_KEYUP, vk_code, 0)
except Exception as e:
print(f"处理滚轮事件失败: {str(e)}")
continue
# 处理鼠标点击
elif isinstance(event, mouse.ButtonEvent):
if event.event_type == mouse.DOWN:
if event.button == mouse.LEFT:
win32gui.PostMessage(target_hwnd, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, lparam)
elif event.button == mouse.RIGHT:
win32gui.PostMessage(target_hwnd, win32con.WM_RBUTTONDOWN, win32con.MK_RBUTTON, lparam)
elif event.event_type == mouse.UP:
if event.button == mouse.LEFT:
win32gui.PostMessage(target_hwnd, win32con.WM_LBUTTONUP, 0, lparam)
elif event.button == mouse.RIGHT:
win32gui.PostMessage(target_hwnd, win32con.WM_RBUTTONUP, 0, lparam)
# 处理鼠标移动
elif isinstance(event, mouse.MoveEvent):
win32gui.PostMessage(target_hwnd, win32con.WM_MOUSEMOVE, 0, lparam)
except Exception as e:
print(f"同步到窗口 {target_hwnd} 失败: {str(e)}")
continue
except Exception as e:
print(f"处理鼠标事件失败: {str(e)}")
def on_keyboard_event(self, event):
# 改进的键盘事件处理
try:
if self.is_syncing:
current_window = win32gui.GetForegroundWindow()
# 检查是否是主控窗口或其插件窗口
is_master = current_window == self.master_window
master_popups = self.get_chrome_popups(self.master_window)
is_popup = current_window in master_popups
if is_master or is_popup:
# 获取实际的输入目标窗口
input_hwnd = win32gui.GetFocus()
# 同步到其他窗口
for hwnd in self.sync_windows:
try:
# 确定目标窗口
if is_master:
target_hwnd = hwnd
else:
# 查找对应的扩展程序窗口
target_popups = self.get_chrome_popups(hwnd)
# 按照相对位置匹配
best_match = None
min_diff = float('inf')
for popup in target_popups:
popup_rect = win32gui.GetWindowRect(popup)
master_rect = win32gui.GetWindowRect(current_window)
# 计算相对位置差异
master_rel_x = master_rect[0] - win32gui.GetWindowRect(self.master_window)[0]
master_rel_y = master_rect[1] - win32gui.GetWindowRect(self.master_window)[1]
popup_rel_x = popup_rect[0] - win32gui.GetWindowRect(hwnd)[0]
popup_rel_y = popup_rect[1] - win32gui.GetWindowRect(hwnd)[1]
diff = abs(master_rel_x - popup_rel_x) + abs(master_rel_y - popup_rel_y)
if diff < min_diff:
min_diff = diff
best_match = popup
target_hwnd = best_match if best_match else hwnd
if not target_hwnd:
continue
# 处理 Ctrl 组合键
if keyboard.is_pressed('ctrl'):
# 发送 Ctrl 按下
win32gui.PostMessage(target_hwnd, win32con.WM_KEYDOWN, win32con.VK_CONTROL, 0)
# 处理常用组合键
if event.name in ['a', 'c', 'v', 'x']:
vk_code = ord(event.name.upper())
if event.event_type == keyboard.KEY_DOWN:
win32gui.PostMessage(target_hwnd, win32con.WM_KEYDOWN, vk_code, 0)
win32gui.PostMessage(target_hwnd, win32con.WM_KEYUP, vk_code, 0)
win32gui.PostMessage(target_hwnd, win32con.WM_KEYUP, win32con.VK_CONTROL, 0)
continue
# 处理普通按键
if event.name in ['enter', 'backspace', 'tab', 'esc', 'space',
'up', 'down', 'left', 'right', # 添加左右键
'home', 'end', 'page up', 'page down', 'delete']:
vk_map = {
'enter': win32con.VK_RETURN,
'backspace': win32con.VK_BACK,
'tab': win32con.VK_TAB,
'esc': win32con.VK_ESCAPE,
'space': win32con.VK_SPACE,
'up': win32con.VK_UP,
'down': win32con.VK_DOWN,
'left': win32con.VK_LEFT,
'right': win32con.VK_RIGHT,
'home': win32con.VK_HOME,
'end': win32con.VK_END,
'page up': win32con.VK_PRIOR,
'page down': win32con.VK_NEXT,
'delete': win32con.VK_DELETE
}
vk_code = vk_map[event.name]
else:
# 处理普通字符
if len(event.name) == 1:
vk_code = win32api.VkKeyScan(event.name[0]) & 0xFF
if event.event_type == keyboard.KEY_DOWN:
# 发送字符消息
win32gui.PostMessage(target_hwnd, win32con.WM_CHAR, ord(event.name[0]), 0)
continue
else:
continue
# 发送按键消息
if event.event_type == keyboard.KEY_DOWN:
win32gui.PostMessage(target_hwnd, win32con.WM_KEYDOWN, vk_code, 0)
else:
win32gui.PostMessage(target_hwnd, win32con.WM_KEYUP, vk_code, 0)
# 释放组合键
if keyboard.is_pressed('ctrl'):
win32gui.PostMessage(target_hwnd, win32con.WM_KEYUP, win32con.VK_CONTROL, 0)
except Exception as e:
print(f"同步到窗口 {target_hwnd} 失败: {str(e)}")
except Exception as e:
print(f"处理键盘事件失败: {str(e)}")
def stop_sync(self):
# 停止同步
try:
self.is_syncing = False
# 移除键盘钩子
if self.keyboard_hook:
keyboard.unhook(self.keyboard_hook)
self.keyboard_hook = None
# 移除鼠标钩子
if self.mouse_hook_id:
mouse.unhook(self.mouse_hook_id)
self.mouse_hook_id = None
# 等待监控线程结束
if self.hook_thread and self.hook_thread.is_alive():
self.hook_thread.join(timeout=1.0)
# 清理资源(保留主窗口设置)
self.sync_windows.clear()
self.popup_mappings.clear()
# 清理调试端口映射
self.debug_ports.clear()
# 重置鼠标状态
self.last_mouse_position = (0, 0)
self.last_move_time = 0
# 更新按钮状态
if self.sync_button:
self.sync_button.configure(text="▶ 开始同步", style='Accent.TButton')
except Exception as e:
print(f"停止同步失败: {str(e)}")
def on_closing(self):
# 窗口关闭事件
try:
self.stop_sync()
# 清理快捷键
if self.shortcut_hook:
keyboard.clear_all_hotkeys()
keyboard.unhook_all()
self.shortcut_hook = None
self.save_settings()
except Exception as e:
print(f"程序关闭时出错: {str(e)}")
finally:
self.root.destroy()
def auto_arrange_windows(self):
"""自动排列窗口"""
try:
# 先停止同步
was_syncing = self.is_syncing
if was_syncing:
self.stop_sync()
# 获取选中的窗口并按编号排序
selected = []
for item in self.window_list.get_children():
if self.window_list.set(item, "select") == "√":
values = self.window_list.item(item)['values']
if values and len(values) >= 5:
number = int(values[1])
hwnd = int(values[4])
selected.append((number, hwnd, item))
if not selected:
messagebox.showinfo("提示", "请先选择要排列的窗口!")
return
# 按编号正序排序
selected.sort(key=lambda x: x[0])
# 获取选中的屏幕信息
screen_index = self.screen_combo.current()
if screen_index < 0 or screen_index >= len(self.screens):
messagebox.showerror("错误", "请选择有效的屏幕!")
return
screen = self.screens[screen_index]
screen_rect = screen['work_rect'] # 使用工作区而不是完整显示区
# 计算屏幕尺寸
screen_width = screen_rect[2] - screen_rect[0]
screen_height = screen_rect[3] - screen_rect[1]
# 计算最佳布局
count = len(selected)
cols = int(math.sqrt(count))
if cols * cols < count:
cols += 1
rows = (count + cols - 1) // cols
# 计算窗口大小
width = screen_width // cols
height = screen_height // rows
# 创建位置映射(从左到右,从上到下)
positions = []
for i in range(count):
row = i // cols
col = i % cols
x = screen_rect[0] + col * width
y = screen_rect[1] + row * height
positions.append((x, y))
# 应用窗口位置
for i, (_, hwnd, _) in enumerate(selected):
try:
x, y = positions[i]
# 确保窗口可见并移动到指定位置
win32gui.ShowWindow(hwnd, win32con.SW_RESTORE)
# 先设置窗口样式确保可以移动
style = win32gui.GetWindowLong(hwnd, win32con.GWL_STYLE)
style |= win32con.WS_SIZEBOX | win32con.WS_SYSMENU
win32gui.SetWindowLong(hwnd, win32con.GWL_STYLE, style)
# 移动窗口
win32gui.MoveWindow(hwnd, x, y, width, height, True)
# 强制重绘
win32gui.UpdateWindow(hwnd)
except Exception as e:
print(f"移动窗口 {hwnd} 失败: {str(e)}")
continue
# 如果之前在同步,重新开启同步
if was_syncing:
self.start_sync([item for _, _, item in selected])
except Exception as e:
messagebox.showerror("错误", f"自动排列失败: {str(e)}")
def custom_arrange_windows(self):
# 自定义排列窗口
try:
# 先停止同步
was_syncing = self.is_syncing
if was_syncing:
self.stop_sync()
selected = []
for item in self.window_list.get_children():
if self.window_list.set(item, "select") == "√":
selected.append(item)
if not selected:
messagebox.showinfo("提示", "请选择要排列的窗口!")
return
try:
# 获取参数
start_x = int(self.start_x.get())
start_y = int(self.start_y.get())
width = int(self.window_width.get())
height = int(self.window_height.get())
h_spacing = int(self.h_spacing.get())
v_spacing = int(self.v_spacing.get())
windows_per_row = int(self.windows_per_row.get())
# 排列窗口
for i, item in enumerate(selected):