-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAutoLogger.py
More file actions
186 lines (156 loc) · 5.67 KB
/
AutoLogger.py
File metadata and controls
186 lines (156 loc) · 5.67 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
import time
import json
import threading
import tkinter as tk
from datetime import datetime
import win32gui
import queue
from pynput import mouse, keyboard
# ---------- 设置 ----------
json_filename_window = 'event_log.json'
json_filename_input = 'input_log.json'
txt_filename_keyboard = 'keyboard_input.txt'
shift_symbol_map = {
'1': '!', '2': '@', '3': '#', '4': '$', '5': '%',
'6': '^', '7': '&', '8': '*', '9': '(', '0': ')',
'-': '_', '=': '+', '[': '{', ']': '}',
';': ':', "'": '"', ',': '<', '.': '>', '/': '?',
'\\': '|', '`': '~'
}
# ---------- 窗口切换监控 ----------
def get_active_window_title():
hwnd = win32gui.GetForegroundWindow()
if hwnd:
return win32gui.GetWindowText(hwnd)
return None
def monitor_window_switch(event_queue, stop_event):
last_title = None
while not stop_event.is_set():
title = get_active_window_title()
if title and title != last_title:
now_time = time.time()
print(f"[{datetime.fromtimestamp(now_time)}] 窗口切换: {title}")
event_queue.put({"time": now_time, "title": title})
last_title = title
time.sleep(0.2)
def save_events_periodically(root, event_queue, data, stop_event):
updated = False
while not event_queue.empty():
event = event_queue.get()
data['events'].append(event)
updated = True
if updated:
with open(json_filename_window, 'w', encoding='utf-8') as f:
json.dump(data, f, indent=2)
if not stop_event.is_set():
root.after(200, save_events_periodically, root, event_queue, data, stop_event)
# ---------- 键鼠记录 ----------
keyboard_log = []
mouse_moves = []
mouse_clicks = []
start_time = datetime.now()
def now():
return (datetime.now() - start_time).total_seconds()
shift_keys = {"Key.shift", "Key.shift_l", "Key.shift_r"}
def on_press(key):
try:
k_str = key.char
except AttributeError:
k_str = str(key)
keyboard_log.append({'key': k_str, 'type': 'press', 'time': now()})
def on_release(key):
try:
k_str = key.char
except AttributeError:
k_str = str(key)
keyboard_log.append({'key': k_str, 'type': 'release', 'time': now()})
if key == keyboard.Key.esc:
return False
def on_move(x, y):
mouse_moves.append({'x': x, 'y': y, 'time': now()})
def on_click(x, y, button, pressed):
mouse_clicks.append({
'x': x, 'y': y, 'button': str(button),
'pressed': pressed, 'time': now()
})
def save_keyboard_txt(keyboard_log, output_path=txt_filename_keyboard):
shift_state = False
text_output = ""
for event in keyboard_log:
k = event['key']
etype = event['type']
# 动态维护shift状态
if k in shift_keys:
if etype == 'press':
shift_state = True
elif etype == 'release':
shift_state = False
continue # shift键本身不输出字符
# 只对按键按下事件生成字符
if etype != 'press':
continue
# 常用特殊键映射
if k == "Key.enter":
text_output += "\n"
elif k == "Key.space":
text_output += " "
elif len(k) == 1 and ord(k) >= 32:
# 可见字符,依据shift状态转换
if shift_state:
if k in shift_symbol_map:
text_output += shift_symbol_map[k]
else:
text_output += k.upper()
else:
text_output += k
else:
# 可按需扩展其他特殊键处理,比如Tab, Backspace等
pass
with open(output_path, "w", encoding="utf-8") as f:
f.write(text_output)
print(f"键盘文本已保存为 {output_path}")
# ---------- 主程序 ----------
def main():
start_timestamp = time.time()
data_window = {"start_time": start_timestamp, "events": []}
with open(json_filename_window, 'w', encoding='utf-8') as f:
json.dump(data_window, f, indent=2)
event_queue = queue.Queue()
stop_event = threading.Event()
monitor_thread = threading.Thread(
target=monitor_window_switch,
args=(event_queue, stop_event),
daemon=True
)
monitor_thread.start()
kb_listener = keyboard.Listener(on_press=on_press, on_release=on_release)
ms_listener = mouse.Listener(on_move=on_move, on_click=on_click)
kb_listener.start()
ms_listener.start()
root = tk.Tk()
root.title("监听程序 - 按 ESC 退出")
root.geometry("450x120")
label = tk.Label(root, text="程序已启动,监听窗口切换中...\n按 ESC 键退出程序", font=("Arial", 12))
label.pack(pady=30)
def on_ui_key(event):
if event.keysym == 'Escape':
print("检测到 ESC,准备退出程序...")
stop_event.set()
root.destroy()
root.bind('<Key>', on_ui_key)
root.after(200, save_events_periodically, root, event_queue, data_window, stop_event)
root.mainloop()
kb_listener.join()
ms_listener.stop()
with open(json_filename_window, "w", encoding="utf-8") as f:
json.dump(data_window, f, indent=2)
with open(json_filename_input, "w", encoding="utf-8") as f:
json.dump({
'keyboard': keyboard_log,
'mouse_moves': mouse_moves,
'mouse_clicks': mouse_clicks
}, f, indent=2)
print("输入事件已保存为", json_filename_input)
save_keyboard_txt(keyboard_log)
if __name__ == '__main__':
main()