之前接了个单,需求是对一个炒股软件使用pywin32库自动化输入股票代码,速度要快,考虑到是软件自动化便答应了下来,开始遇到的难度是如何运行代码后自动切换到对应的软件窗口,对于多窗口,如何指定窗口输入指令,尝试了很多方法后都没有实现,后面通过获取子窗口句柄,然后将该句柄置顶并最大化即可实现,具体代码如下
import win32api
import win32con
import win32gui
import win32com.client
import re
import time
def huiche(): # 回车操作
win32api.keybd_event(13, 0, 0, 0) # enter键位码
win32api.keybd_event(13, 0, win32con.KEYEVENTF_KEYUP, 0) # 释放按键
def anjian(num):
win32api.keybd_event(num, 0, 0, 0) #
win32api.keybd_event(num, 0, win32con.KEYEVENTF_KEYUP, 0) # 释放按键
class cWindow:
def __init__(self):
self._hwnd = None
self.shell = win32com.client.Dispatch("WScript.Shell")
def BringToTop(self):
win32gui.BringWindowToTop(self._hwnd)
def SetAsForegroundWindow(self):
self.shell.SendKeys('%')
win32gui.SetForegroundWindow(self._hwnd)
def Maximize(self):
win32gui.ShowWindow(self._hwnd, win32con.SW_MAXIMIZE)
def setActWin(self):
win32gui.SetActiveWindow(self._hwnd)
def _window_enum_callback(self, hwnd, wildcard):
'''Pass to win32gui.EnumWindows() to check all the opened windows'''
if re.match(wildcard, str(win32gui.GetWindowText(hwnd))) is not None:
self._hwnd = hwnd
def find_window_wildcard(self, wildcard):
self._hwnd = None
win32gui.EnumWindows(self._window_enum_callback, wildcard)
def kill_task_manager(self):
wildcard = 'Gestionnaire des t.+ches de Windows'
self.find_window_wildcard(wildcard)
if self._hwnd:
win32gui.PostMessage(self._hwnd, win32con.WM_CLOSE, 0, 0)
if __name__ == '__main__':
jianma_zd = {}
for i,j in zip(range(0,10),range(96,106)):
jianma_zd[str(i)] = j
print(jianma_zd)
code = input('输入代码:')
first_num = code[0]
last_num = code[1:]
wildcard = ".*通达信金融终端.*"
cW = cWindow()
cW.kill_task_manager()
cW.find_window_wildcard(wildcard)
cW.BringToTop()
cW.Maximize()
cW.SetAsForegroundWindow()
time.sleep(0.5)
print(first_num)
anjian(jianma_zd.get(first_num))
time.sleep(0.3)
for num in last_num:
anjian(jianma_zd.get(num))
time.sleep(0.1)
huiche()
点击此处登录后即可评论