-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathwincore.py
323 lines (288 loc) · 17.6 KB
/
wincore.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
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtCore import QTimer,QRegExp
from PyQt5.QtGui import QRegExpValidator
from winshell import Ui_MainWindow
import run
from loguru import logger
import os
# import sys
import pyWinhook
# import pythoncom
import time
import json
import configparser
import threading
import webbrowser
class wincore (QtWidgets.QMainWindow,Ui_MainWindow):
def __init__(self):
super(wincore,self).__init__()
self.setupUi(self)
self.init()
#读取config.ini中的配置
def readConfig(self):
try:
logger.info("read config.....")
config = configparser.ConfigParser()
config.read('config.ini')
self.mouseCmdInterval = config.getint('winCfg', 'mouseCmdInterval')
self.shortcutKeys={'start':config.get('winCfg', 'startKey'),'stop':config.get('winCfg', 'stopKey'),'capture':config.get('winCfg', 'captureKey'),"stopRecord":config.get('winCfg', 'stopRecordKey')}
self.scriptsPath = config.get('winCfg',"scriptsPath").strip("\"")
except:
logger.error("read config error")
self.mouseCmdInterval = 200
self.shortcutKeys={'start':'F9','stop':'F10','capture':'F8',"stopRecord":'F7'}
self.scriptsPath = "./scripts/"
logger.info(self.shortcutKeys['start']+" "+self.shortcutKeys['stop'])
logger.info(self.shortcutKeys['capture']+" "+self.shortcutKeys['stopRecord'])
logger.info(self.scriptsPath)
def init(self):
self.nowMousePos = ""
self.Captureflag = False #实时抓取鼠标位置标志位
self.eventTagTime = 0 #保存上一次鼠标或者键盘事件时间
self.creatScripts = False #是否开始录制标志位
self.record = [] #缓存录制脚本
self.shortcutKeys={} #保存快捷键
#self.lastStatusBarMsg = ""
self.readConfig()
self.setWindowTitle('自动化工具')
self.statusBar=QStatusBar()
self.setStatusBar(self.statusBar)
self.statusBar.showMessage('这是一个鼠标键盘自动化执行工具',5000)
#根据快捷键显示UI
self.pushButton.setText("开始("+self.shortcutKeys['start'].replace("\"","")+")")
self.pushButton_2.setText("停止("+self.shortcutKeys['stop'].replace("\"","")+")")
self.pushButton_6.setText("停止("+self.shortcutKeys['stopRecord'].replace("\"","")+")")
self.label_6.setText(self.shortcutKeys['capture'].replace("\"","")+"单次抓取")
if(os.path.exists(self.scriptsPath) ==False):#如果没有这个而文件夹
os.mkdir("scripts")
logger.debug("not find scripts,mkdir it")
self.reloadScriptsList()
# for file in os.listdir("./scripts"):
# logger.debug(file)
# if(file.endswith(".txt")):#只加载txt文件
# self.comboBox.addItem("./scripts/"+file)
# 限制输入正整数
reg = QRegExp("^[0-9]*[1-9][0-9]*$")
LE1Validator = QRegExpValidator(self)
LE1Validator.setRegExp(reg)
self.lineEdit.setValidator(LE1Validator)
# 绑定按键
self.pushButton.clicked.connect(self.buttonStart)
self.pushButton_2.clicked.connect(self.buttonStop)
self.pushButton_3.clicked.connect(self.buttonCapture)
self.pushButton_4.clicked.connect(self.buttonCaptureStop)
self.pushButton_5.clicked.connect(self.buttonRecord)
self.pushButton_6.clicked.connect(self.buttonRecordStop)
#菜单事件
self.creatExample.triggered.connect(self.creatExampleScripts)
self.openCfg.triggered.connect(self.openConfig)
self.setCfg.triggered.connect(self.reloadConfig)
self.refresh.triggered.connect(self.reloadScriptsList)
self.NetExample.triggered.connect(self.netExample)
self.NetScriptsHelp.triggered.connect(self.netScriptsHelp)
# 实例脚本执行器
self.runnerThread = run.Runner()
self.runnerThread.start()
#默认值
self.setCycleCount("1")
#状态更新定时器
self.timer = QTimer() # 初始化定时器
self.timer.timeout.connect(self.statusUpdate)
#开启监听
hm = pyWinhook.HookManager()
#键盘
hm.KeyAll = self.onKeyboardEvent
hm.HookKeyboard()
# 监听鼠标
hm.MouseAll = self.onMouseEvent
hm.HookMouse()
#重新加载脚本列表
def reloadScriptsList(self):
self.comboBox.clear()
#for file in os.listdir("./scripts"):
for file in os.listdir(self.scriptsPath):
if(file.endswith(".txt")):#只加载txt文件
self.comboBox.addItem(self.scriptsPath+file)
def setCycleCount(self,count):
self.lineEdit.setText(count)
def getCycleCount(self):
return self.lineEdit.text()
def setMousePos(self,pos):
self.lineEdit_2.setText(pos)
def getScriptsPath(self):
return self.comboBox.currentText()
def buttonStart(self):
if(self.runnerThread.getFlag() == True):
self.statusBar.showMessage('已经在运行,勿重复点击',3000)
return True
self.showMinimized()# 最小状态
#self.statusBar.showMessage('scripts start',3000)
self.runnerThread.setScritpsPath(self.getScriptsPath())
self.runnerThread.setCount(int(self.getCycleCount()))
self.runnerThread.go()
self.timer.start(100)
def buttonStop(self):
self.activateWindow() #恢复状态
self.runnerThread.suspend()
self.timer.stop()
self.statusBar.showMessage('已手动停止脚本',3000)
def buttonCapture(self):
self.Captureflag = True
self.statusBar.showMessage('开始抓取',3000)
def buttonCaptureStop(self):
self.Captureflag = False
self.statusBar.showMessage('停止抓取',3000)
def buttonRecord(self):
self.creatScripts = True
self.pushButton_5.setEnabled(False)
#最小化
self.showMinimized()
self.statusBar.showMessage('开始录制脚本',3000)
def buttonRecordStop(self):
self.statusBar.showMessage('停止录制',3000)
if(not self.record):#如果啥也没录到则直接退出
return True
# 根据输入文字建立新的脚本
name = self.lineEdit_3.text()
if(name == ""):
self.statusBar.showMessage('脚本未命名,使用默认名称',3000)
name = "newScripts"
#path = "./scripts/"+name+".txt"
path = self.scriptsPath+name+".txt"
output = json.dumps(self.record, indent=1)
output = output.replace('\r\n', '\n').replace('\r', '\n')
output = output.replace('\n ', '').replace('\n ', '')
output = output.replace('\n ]', ']')
open(path,"w").write(output)
self.record = []
self.creatScripts = False
self.pushButton_5.setEnabled(True)
#录制完刷新一下下拉菜单
self.reloadScriptsList()
# self.comboBox.clear()
# for file in os.listdir("./scripts"):
# if(file.endswith(".txt")):#只加载txt文件
# self.comboBox.addItem("./scripts/"+file)
def closeEvent(self,event):
self.runnerThread.close()
def statusUpdate(self):
self.label_3.setText( str(self.runnerThread.getNowCmdLog()))
# 更新消息提示栏
#if(self.runnerThread.getStatus()!="" and self.runnerThread.getStatus()!=self.lastStatusBarMsg):
#self.lastStatusBarMsg = self.runnerThread.getStatus()
#self.statusBar.showMessage(self.lastStatusBarMsg,3000)
msg = self.runnerThread.getStatus()
if(msg != ""):
self.statusBar.showMessage(msg,3000)
if(msg.find("[E]")>=0): #由于错误停止运行
self.showNormal()
self.activateWindow()
if(msg.find("[O]")>=0): #执行完成正常停止
self.showNormal()
self.activateWindow()
def getNowTime(self):
return int(time.time() * 1000)
# 监听键盘事件
def onKeyboardEvent(self,event):
#print('MessageName:',event.MessageName,'kk:',event.Key)
if(event.Key == self.shortcutKeys['start'].replace("\"","")):#启动脚本
logger.info("start!")
self.showMinimized()
self.buttonStart()
elif(event.Key == self.shortcutKeys['stop'].replace("\"","")):#停止脚本
self.showNormal()
self.activateWindow()
self.buttonStop()
logger.info("stop!")
elif(event.Key == self.shortcutKeys['capture'].replace("\"","")):#抓取鼠标位置
self.setMousePos(self.nowMousePos)
elif(event.Key ==self.shortcutKeys['stopRecord'].replace("\"","")):#停止录制
self.showNormal()
self.activateWindow()
self.buttonRecordStop()
else: # 排除快捷键
if(self.creatScripts):
if(not self.record): #如果是新脚本则默认第一个指令前延时5秒
delay = 5000
else:
delay = self.getNowTime() - self.eventTagTime
# [1000,"keyboard","down","a"],
self.eventTagTime = self.getNowTime()
#获取类型
if(event.MessageName == "key down" or event.MessageName == "key sys down"): # alt的类型是 key sys down
keyType = "down"
elif(event.MessageName == "key up"):
keyType = "up"
else:
logger.debug("this MessageName not save ",event.MessageName)
return #其他类型不处理
log = "record add: " + str(delay) + " " + keyType + " " + event.Key
logger.debug(log)
self.record.append([delay, 'keyboard', keyType, event.Key])
return True
# 监听到鼠标事件调用
def onMouseEvent(self,event):
#log = "mouse record add:" + "00" + " " + event.MessageName + " " + str(event.Position)
#logger.debug(log)
self.nowMousePos = str(event.Position)
if(self.Captureflag == True):
self.setMousePos(str(event.Position))
if(self.creatScripts):
if(not self.record): #如果是新脚本则默认第一个指令前延时5秒
delay = 5000
else:
delay = self.getNowTime() - self.eventTagTime
#这里需要现在鼠标移动的采集率
if(event.MessageName=="mouse move" and delay<=self.mouseCmdInterval):
return True
self.eventTagTime = self.getNowTime()
log = "mouse record add:" + str(delay) + " " + event.MessageName + " " + str(event.Position)
logger.debug(log)
# 修改类型
if(event.MessageName == "mouse left down"):
mouseType = "left down"
elif(event.MessageName == "mouse left up"):
mouseType = "left up"
elif(event.MessageName == "mouse move"):
mouseType = "move"
elif(event.MessageName == "mouse right down"):
mouseType = "right down"
elif(event.MessageName == "mouse right up"):
mouseType = "right up"
else:
return True#其他类型不处理
#存储
self.record.append([delay, 'mouse', mouseType, event.Position])
return True
def creatExampleScripts(self):
h = "[\n"
e = "\n]"
b1 = "[5000,\"keyboard\",\"down\",\"1\"],"
b2 = "\n[142,\"keyboard\",\"up\",\"1\"],"
open(self.scriptsPath+"example.txt","w").write(h + b1 + b2 + e)
self.reloadScriptsList()
def openConfig(self):
if(os.path.exists('config.ini')):
thread = threading.Thread(target=openTxt)
thread.start()
else:
logger.info("open config fail,creat")
runCfgTxt = "[runCfg]\nConfidence = 0.7\n\n"
winCfgTxt = "[winCfg]\nmouseCmdInterval = 200\nstartKey = \"F9\"\nstopKey = \"F10\"\ncaptureKey = \"F8\"\nstopRecordKey = \"F7\"\nscriptsPath = \"./scripts/\""
open("config.ini","w").write(runCfgTxt + winCfgTxt)
thread = threading.Thread(target=openTxt)
thread.start()
def reloadConfig(self):
self.readConfig()
def netExample(self):
webbrowser.open("https://github.com/lissettecarlr/autogui/tree/main/exampleScripts")
def netScriptsHelp(self):
webbrowser.open("https://github.com/lissettecarlr/autogui/blob/main/doc/scripts.md")
def openTxt():
os.system('config.ini')
def windowsOpen(sys):
app=QtWidgets.QApplication(sys.argv)
win=wincore()
win.show()
sys.exit(app.exec_())