from ctypes import * import win32api, win32gui, win32con import time hwnd = win32gui.FindWindow(None, '计算器') rect = win32gui.GetWindowRect(hwnd) x = rect[0] y = rect[1] w = rect[2] - x h = rect[3] - y print("Window %s:" % (win32gui.GetWindowText(hwnd))) print("Location: (%d, %d)" % (x, y)) print("Size: (%d, %d)" % (w, h)) time.sleep(1) windll.user32.SetCursorPos((x + w - 10), (y + 10)) win32api.mouse_event( win32con.MOUSEEVENTF_LEFTDOWN | win32con.MOUSEEVENTF_LEFTUP, 0, 0)
import win32gui import win32api import win32con import keyboard import time import sys tileSize = 16 marginTop = 100 marginLeft = 15 buttonTop = 72 colors = (0xEEEEEE, 0x2196F3, 0x4CAF50, 0xF44336, 0x3F51B5, 0xD50000, 0x009688, 0x9C27B0, 0x212121, 0xED1C24, 0xE0E0E0) # Get window info msxWin = win32gui.FindWindow(None, "Minesweeper X") winRect = win32gui.GetWindowRect(msxWin) cliRect = win32gui.GetClientRect(msxWin) rect = (winRect[0], winRect[1], cliRect[2], cliRect[3]) # Calculate board size width = int((winRect[2] - winRect[0] - 30) / tileSize - 1) height = int((winRect[3] - winRect[1] - 116) / tileSize - 1) around = ((-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)) startSet = ((1/2, 1/2), (1/4, 1/2), (3/4, 1/2), (1/2, 1/4), (1/2, 3/4), (1/4, 1/4), (1/4, 3/4), (3/4, 1/4), (3/4, 3/4)) tilecache = {} # Save the scanned tiles margin = [] # The set of tiles opened but not solved solved = [] # The set of tiles solved # Mouse functions def lclick(x, y): # Left click
import win32gui, win32api, win32con # 获得父容器 pHwnd = win32gui.FindWindow('WTWindow', '验证码识别') # 获取子容器,识别结果输入框 edtextHwnd = win32gui.FindWindowEx(pHwnd, None, 'Edit', '') buf_size = win32gui.SendMessage(edtextHwnd, win32con.WM_GETTEXTLENGTH, 0, 0) + 1 # 要加上截尾的字节 str_buffer = win32gui.PyMakeBuffer(buf_size) # 生成buffer对象 win32api.SendMessage(edtextHwnd, win32con.WM_GETTEXT, buf_size, str_buffer) # 获取buffer print(str_buffer[:-1]) str = str(str_buffer[:-1]) # 转为字符串 result = str print(result) ########################## # 获取识别结果中输入框文本 length = win32gui.SendMessage(edtextHwnd, win32con.WM_GETTEXTLENGTH) + 1 buf = win32gui.PyMakeBuffer(length) #发送获取文本请求 win32api.SendMessage(edtextHwnd, win32con.WM_GETTEXT, length, buf) #下面应该是将内存读取文本 address, length = win32gui.PyGetBufferAddressAndLen(buf[:-1]) text = win32gui.PyGetString(address, length)
import time import win32api import win32gui import win32con # start hwnd = win32gui.FindWindow(0, "阴阳师-网易游戏") win32gui.SetForegroundWindow(hwnd) win32gui.MoveWindow(hwnd, 0, 0, 1152, 650, True) rt = win32gui.GetClientRect(hwnd) str2 = u"%s, %d, %d, %d, %d" % (str, rt[0], rt[1], rt[2], rt[3]) print(str2) # win32api.MessageBox(win32con.NULL, str2, u'Hello Python, 你好呀!', win32con.MB_OK) # win32api.SendMessage(0) # time.sleep(1) # mouse.lefClick(100,100) # win.mouse_click(100,100) # core.startpve() def click1(x, y): # 第一种 win32api.SetCursorPos((x, y)) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x, y, 0, 0) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, x, y, 0, 0) def click2(x, y): # 第二种
#coding=utf-8 #version:semiauto_pickit_a0.1,正式使用版 #updata a0.1:基於v0.5的重寫 from PIL import Image import ImageGrab import os import hashlib import time import pickle import win32gui import win32con import win32api getbrow = win32gui.FindWindow('Chrome_WidgetWin_1', u'立秋·驾培-闯关王 - Google Chrome') ##定义窗口 win32gui.ShowWindow(getbrow, win32con.SW_RESTORE) ##强行显示界面 win32gui.ShowWindow(getbrow, win32con.SW_MAXIMIZE) ##窗口最大化 win32gui.SetForegroundWindow(getbrow) ##将浏览器窗口提到最前 time.sleep(0.8) #等待窗口完全彈出 #檢查工作目錄 if os.path.isdir('tmp'): pass else: os.mkdir('tmp') #定義元素 hashdict = {} hashdict_v2 = {}
def getGame(self): if win32gui.FindWindow(None, "Elite - Dangerous (CLIENT)"): return True else: return False
def get_hwnd(name, clss=None): """ 获取窗口 """ return win32gui.FindWindow(clss, name)
print("++++++++++++++++++++++++++++++++++++") print("") print("") print("") print("请将互动键设置为鼠标中键") input("确认请按回车") server_name = input("请输入你的服务器名称(默认:唯我独尊):") server_name = server_name if server_name else "唯我独尊" server_zone = input("请输入该服务器所在大区(默认:电信五区):") server_zone = server_zone if server_zone else "电信五区" game_window_name = "剑网3 - " + server_name + " @ " + server_zone hwnd = win32gui.FindWindow(0, game_window_name) if hwnd <= 0: print("剑网3未启动,脚本关闭中...") time.sleep(5) exit(0) else: print("已检测到剑网三,请将窗口切换至剑网三,将鼠标指针悬停在剑网三窗口内") print("脚本运行中,请勿关闭此窗口") print("按F8可以暂停/继续脚本") key_listener = Listener(on_release=loop_toggle) key_listener.start() while True: if win32gui.GetWindowText(
def upload(self, params, startTime): self.driver.get("http://"+self.ip+":"+self.port) # 免密码登录 # self.driver.maximize_window() # self.driver.delete_all_cookies() # cookie = {'domain': self.ip, 'httpOnly': False, 'name': 'Authorization', 'path': '/', 'secure': False, 'value': self.cookieValue } # self.driver.add_cookie(cookie) # self.driver.refresh() # 登录 time.sleep(5) loginForms = self.driver.find_elements_by_class_name("login-form-panel") loginForm = "" for item in loginForms: if item.is_displayed(): loginForm = item userNameInput = loginForm.find_elements_by_class_name("el-input__inner") for item in userNameInput: if "请输入用户名" == item.get_property("placeholder"): item.clear() item.send_keys(self.user) elif "请输入密码" == item.get_property("placeholder"): item.send_keys(self.psd) loginButton = loginForm.find_element_by_tag_name("button") loginButton.click() time.sleep(5) #进入数据管理页面 mainPage = None time.sleep(5) for waitTime in range(0, 10): try: mainPage = self.driver.find_element_by_class_name("full-container") break except NoSuchElementException: time.sleep(1) if not mainPage: self.driver.quit() return navwrap = self.driver.find_element_by_class_name("nav-wrap") menuList = navwrap.find_elements_by_tag_name("a") chengedPage = False for menu in menuList: if "数据管理" == menu.text: menu.click() chengedPage = True time.sleep(3) break if not chengedPage: print("未找到数据管理菜单") self.driver.quit() return # 选择要上传到的文件夹 folderFilterTree = None for waitTime in range(0,10): try: folderFilterTree = self.driver.find_element_by_id("filterTree") break except NoSuchElementException: time.sleep(1) # 点击上传 operbtns =self.driver.find_element_by_class_name("oper-btns") uploadButton = operbtns.find_element_by_class_name("el-dropdown") for param in params: respons = requests.request(method="GET", url="http://192.168.4.46:8310/user/jwt/time") while int(startTime) > int(respons.text): respons = requests.request(method="GET", url="http://192.168.4.46:8310/user/jwt/time") if int(startTime) == int(respons.text): break uploadButton.click() for i in range(0, 5): time.sleep(2) try: dropdownmenu = self.driver.find_elements_by_class_name("el-dropdown-menu") liList = dropdownmenu[len(dropdownmenu)-1].find_elements_by_tag_name("li") findTagFileType = False for li in liList: if param["fileType"] == li.get_property("title"): li.click() findTagFileType = True break if findTagFileType: time.sleep(3) dialog = win32gui.FindWindow('#32770', u'打开') # 找到windows对话框参数是(className,title) ComboBoxEx32 = win32gui.FindWindowEx(dialog, 0, 'ComboBoxEx32', None) ComboBox = win32gui.FindWindowEx(ComboBoxEx32, 0, 'ComboBox', None) Edit = win32gui.FindWindowEx(ComboBox, 0, 'Edit', None) # 上面3句依次找对象,直到找出输入框Edit对象的句柄 button = win32gui.FindWindowEx(dialog, 0, 'Button', None) # 确定按钮 win32gui.SendMessage(Edit, win32con.WM_SETTEXT, 0, param["filepath"]) win32gui.SendMessage(dialog, win32con.WM_COMMAND, 1, button) time.sleep(5) break else: print("未找到【"+param["fileType"]+"】类型文件上传按钮") break except NoSuchElementException: print("未找到【" + param["fileType"] + "】类型文件上传按钮1") time.sleep(1) uploadButton.click()
def log_in_hs(acc): logging.info('miner No.' + str(player_id) + ' player starts.') # open in battle net login window loginbt = LoginWindow(bn_target, '战网登录', acc['acc'], acc['psw']) logged_in = False logging_time = time.time() bt_window = 0 while not logged_in: bn_hwnd = False while not bn_hwnd: loginbt.runbnet() bn_hwnd = loginbt.findWindow() loginbt.login() # wait for the battle net window shows up time_login = time.time() while time.time() - time_login <= 30: bt_window = win32gui.FindWindow(None, '战网') if bt_window > 0: logged_in = True logging.info('logging No.' + str(player_id) + ' player succeeded!') break # click cancel pyautogui.moveTo(1100, 1020, 1, pyautogui.easeInQuad) time.sleep(0.5) pyautogui.click() pyautogui.moveTo(1100, 1220, 1, pyautogui.easeInQuad) time.sleep(0.5) pyautogui.click() if not logged_in: kill_process('Battle.net.exe', '战网登录') logging.warning('log No.' + str(player_id) + ' player failed!') if time.time() - logging_time >= 1200000000: # after 10 minutes failure, terminate program logging.warning('logging keeps failing, terminated!') sys.exit() # logged in Battle net!!! # move bn window to 0,0 win32gui.SetForegroundWindow(bt_window) bt_rec = win32gui.GetWindowRect(bt_window) win32gui.MoveWindow(bt_window, 0, 0, bt_rec[2] - bt_rec[0], bt_rec[3] - bt_rec[1], 1) time.sleep(1) # looking for hs and click waiting for hs hs_png = 'hs_sur.png' time.sleep(10) # while True: # found = pyautogui.locateCenterOnScreen(hs_png, region=(0, 0, bt_rec[2], bt_rec[3]), # grayscale=False, confidence=0.7) # if found is not None: # x = found[0] # y = found[1] # break # # logging.info('hs logo found in (' + str(x) + ', ' + str(y) + ')!') # pyautogui.moveTo(x, y, 1, pyautogui.easeInQuad) # # pyautogui.click(x, y) time.sleep(1) login_png = 'login_sur.png' time.sleep(9) pyautogui.doubleClick(1034, 49) while True: found = pyautogui.locateCenterOnScreen(login_png, region=(100, 1200, 400, 100), grayscale=False, confidence=0.7) if found is not None: x = found[0] y = found[1] logging.info('found the login button!') break pyautogui.moveTo(x, y, 1, pyautogui.easeInQuad) pyautogui.click(x, y) logging.info('hs log in button was pressed!') # waiting for hs running hs_is_running = False hs_window = 0 logging.info('waiting for hstone loaded...') while not hs_is_running: hs_window = win32gui.FindWindow(None, '炉石传说') if hs_window > 0: hs_is_running = True logging.info('hstone loaded successfully!') win32gui.SetForegroundWindow(hs_window) win32gui.MoveWindow(hs_window, 620, 0, 800, 600, 1) return hs_window
def runbnet(self): exist = win32gui.FindWindow(None, self.windowName) if exist == 0: win32api.WinExec(self.programDir) return
for i in range(11): e[i] = [0] * 11 # Power of vertices pw = [0] * 11 # Start point st = -1 path = [] hexagon = cv2.imread("hexagon.png") rd = cv2.imread("ready.png") # Edge wh = cv2.imread("edge.png") wh = cv2.cvtColor(wh, cv2.COLOR_BGR2HSV) _, wh = cv2.threshold(wh, -1, 255, cv2.THRESH_BINARY) win32gui.SetForegroundWindow(win32gui.FindWindow(None, "Andy")) time.sleep(2) def updateScreen(): screen = ImageGrab.grab() screen.save("screen.png", "png") screen = cv2.imread("screen.png") main = screen[200:590, 512:853] main = cv2.resize(main, (220, 220 * main.shape[0] / main.shape[1])) main = cv2.cvtColor(main, cv2.COLOR_BGR2HSV) _, main = cv2.threshold(main, 0, 255, cv2.THRESH_BINARY) return (screen, main) def getNumHexs():
def close_dialog_box(self): while win32gui.FindWindow(None, "Windows Script Host")>0: #time.sleep(0.21) win32gui.SendMessage(win32gui.FindWindow(None, "Windows Script Host"),win32con.WM_CLOSE)
def __init__(self, string=None): self.window_text = string self.window_handle = win32gui.FindWindow(None, self.window_text)
def startDownload(self, downloadUrls): gdi32 = windll.gdi32 user32 = windll.user32 hdc = user32.GetDC(None) win32clipboard.OpenClipboard() win32clipboard.EmptyClipboard() win32clipboard.SetClipboardData(win32con.CF_TEXT, "") win32clipboard.CloseClipboard() os.startfile(self.xunleiExePath) wndMain = None while not wndMain: time.sleep(1) wndMain = win32gui.FindWindow(None, u"迅雷") print wndMain #main window point wndMainRect = win32gui.GetWindowRect(wndMain) self.leftMouseClick(wndMainRect[0] + 35, wndMainRect[1] + 100) time.sleep(0.1) win32clipboard.OpenClipboard() win32clipboard.EmptyClipboard() #win32clipboard.SetClipboardData(win32con.CF_TEXT, downloadUrls.decode('utf-8').encode('gbk')) win32clipboard.SetClipboardData(win32con.CF_TEXT, downloadUrls) win32clipboard.CloseClipboard() wndCreateDownload = win32gui.FindWindow(None, u"迅雷") print wndCreateDownload ### open the download window and cv resource in it #if wndCreateDownload: wndCreateDownloadRect = win32gui.GetWindowRect(wndCreateDownload) self.leftMouseClick(wndCreateDownloadRect[0] + 60, wndCreateDownloadRect[1] + 70) self.ctrlV() #self.leftMouseClick(wndCreateDownloadRect[2]+100, wndCreateDownloadRect[3]-100) ##after window show then cv resource time.sleep(0.5) c = gdi32.GetPixel(hdc, wndCreateDownloadRect[0] + 150, wndCreateDownloadRect[1] + 215) chex = hex(c) #win32api.SetCursorPos([wndCreateDownloadRect[0] + 150,wndCreateDownloadRect[1]+ 215]) """ [1]right or left [3] top or buttom """ self.leftMouseClick(wndCreateDownloadRect[1] + 850, wndCreateDownloadRect[3] - 280) if ((chex == "0xfefefe") or (chex == "0xffffff")): # 开始下载 time.sleep(3) print 'downlaod ...' self.leftMouseClick(wndCreateDownloadRect[1] + 850, wndCreateDownloadRect[3] - 150) else: print 'url faild' self.leftMouseClick(wndCreateDownloadRect[2] - 30, wndCreateDownloadRect[1] + 15) print "close download button" alreadyExistDlg = win32gui.FindWindowEx(None, None, 'XLUEModalHostWnd', "MessageBox") if alreadyExistDlg: alreadyExistDlgRect = win32gui.GetWindowRect(alreadyExistDlg) self.leftMouseClick(alreadyExistDlgRect[0] + 390, alreadyExistDlgRect[1] + 35)
) print("Exiting OSC thread") print("Opening slideset") my_slide = ppt() time.sleep(1) my_slide.start_slideshow() time.sleep(2) filename = str(SLIDESHOW_PATH).split('\\').pop() window_name = "Diaporama Powerpoint - " + filename + " - PowerPoint" print("looking for window named : ", window_name) hwnd = win32gui.FindWindow(None, window_name) print("handle : ", hwnd) if (hwnd != 0): win32gui.MoveWindow(hwnd, 0, 0, 600, 400, True) print("starting OSC thread") dispatcher = dispatcher.Dispatcher() x = threading.Thread(target=osc_thread, args=(1, )) x.start() def obs_connect(): global obs_connected try: print("Connecting to OBS\n")
def getLauncher(self): if win32gui.FindWindow(None, "Elite Dangerous Launcher"): return True else: return False
# Config specification for logging file logging.basicConfig(filename='DougsESP.log', level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s', filemode="w") logger = logging.getLogger() # Offset values for the text labels from the circles we draw to the screen TEXT_OFFSET_X = 13 TEXT_OFFSET_Y = -5 # Information on SoT height and width. Used here and in main.py to display # data to the screen. May need to manually override if wonky try: window = win32gui.FindWindow(None, "Sea of Thieves") SOT_WINDOW = win32gui.GetWindowRect(window) # (x1, y1, x2, y2) SOT_WINDOW_H = SOT_WINDOW[3] - SOT_WINDOW[1] SOT_WINDOW_W = SOT_WINDOW[2] - SOT_WINDOW[0] except Exception as e: logger.error("Unable to find Sea of Thieves window; exiting.") exit(-1) # Creates a pyglet "Batch" that we draw our information to. Effectively serves # as a piece of paper, so we save render cost because its 2D main_batch = Batch() # Load our offset json file with open("offsets.json") as infile: OFFSETS = json.load(infile)
def find_window(title): hwnd = win32gui.FindWindow(None, title) assert hwnd win32gui.SetForegroundWindow(hwnd) return win32gui.GetWindowRect(hwnd)
import win32api, win32gui, win32con import win32com.client shell = win32com.client.Dispatch("WScript.Shell") shell.Run("calc") win32api.Sleep(1000) shell.SendKeys("200{+}") win32api.Sleep(1000) shell.SendKeys("{(}100\x2a2{)}") win32api.Sleep(1000) shell.SendKeys("-22") win32api.Sleep(1000) shell.SendKeys("=") h = win32gui.FindWindow("SciCalc", None) edit = win32gui.FindWindowEx(h, None, 'Edit', None) bufLen = 1024 buf = win32gui.PyMakeBuffer(bufLen) n = win32gui.SendMessage(edit, win32con.WM_GETTEXT, bufLen, buf) print buf[0:n] win32api.Sleep(1000) win32gui.SendMessage(h, win32con.WM_SYSCOMMAND, win32con.SC_CLOSE, 0)
def find_hwnd(title: str): global hwnd if not hwnd: hwnd = win32gui.FindWindow(None, title) return hwnd
from telethon import TelegramClient import socks import win32gui from telethon.tl.functions.account import UpdateProfileRequest classname = '{97E27FAA-C0B3-4b8e-A693-ED7881E99FC1}'# win = win32gui.FindWindow(classname, None) text = win32gui.GetWindowText(win) print(text) api_id = id from https://my.telegram.org/ api_hash = api from ^ client = TelegramClient('session_name', api_id, api_hash).start() client(UpdateProfileRequest( about=text ))
def __init__(self, title_name, screen): # 获取句柄 self.hwnd = win32gui.FindWindow(0, title_name) self.screen = screen
# -*- coding: utf-8 -*- # @Time : 2018/7/1 23:09 # @Author : xuanle # @FileName: win32kou.py # @Software: PyCharm # @GitHub :https://github.com/LeShine import win32con import win32gui notepad = win32gui.FindWindow("Notepad", "无标题 - 记事本") QQ = win32gui.FindWindow("TXGuiFoundation", "QQ") # 找出qq窗体 target = QQ while True: for x in range(800): win32gui.SetWindowPos(target, win32con.HWND_TOPMOST, x, 0, 400, 400, win32con.SWP_SHOWWINDOW) for x in range(800): win32gui.SetWindowPos(target, win32con.HWND_TOPMOST, 600, x, 400, 400, win32con.SWP_SHOWWINDOW) for x in range(800, 0, -1): win32gui.SetWindowPos(target, win32con.HWND_TOPMOST, x, 600, 400, 400, win32con.SWP_SHOWWINDOW) for x in range(800, 0, -1): win32gui.SetWindowPos(target, win32con.HWND_TOPMOST, 0, x, 400, 400, win32con.SWP_SHOWWINDOW) for x in range(800): win32gui.SetWindowPos(target, win32con.HWND_TOPMOST, 300, x, 400, 400, win32con.SWP_SHOWWINDOW) for x in range(800):
import os # .path.join(), .listdir(), .chdir(), .getcwd() 등 사용 import win32com.client as win32 # 한/글 열 수 있는 모듈 import win32gui # 창 숨기기 위한 모듈 os.chdir('c:/to_pdf') # hwp 파일이 있는 폴더로 이동 print(os.listdir()) # 파일목록 출력해보기. 없어도 무관 for i in os.listdir(): # 현재 폴더 안에 있는 모든 파일명에서 os.rename(i, i.replace(' - 복사본 ', '')) # ' - 복사본 ' 부분을 지워줘. hwp = win32.gencache.EnsureDispatch('HWPFrame.HwpObject') # 한/글 열기 hwnd = win32gui.FindWindow(None, '빈 문서 1 - 한글') # 해당 윈도우의 핸들값 찾기 print(hwnd) # 핸들값 출력해보기. 없어도 무관 win32gui.ShowWindow(hwnd, 0) # 한/글 창을 숨겨줘. 0은 숨기기, 5는 보이기, 3은 풀스크린 등 hwp.RegisterModule('FilePathCheckDLL', 'FilePathCheckerModule') # 보안모듈 적용 BASE_DIR = 'c:/to_pdf' # 한/글은 파일 열거나 저장할 때 전체경로를 입력해야 하므로, os.path.join(BASE_DIR, i) 식으로 사용할 것 print(os.getcwd()) # 현재경로 출력. 없어도 무관 print(len(os.listdir())) # 현재폴더 안에 있는 파일 갯수 출력 for i in os.listdir(): # 현재폴더 안에 있는 모든 파일을 hwp.Open(os.path.join(BASE_DIR, i)) # 한/글로 열어서 hwp.HAction.GetDefault( 'FileSaveAsPdf', hwp.HParameterSet.HFileOpenSave.HSet) # PDF로 저장할 건데, 설정값은 아래와 같이. hwp.HParameterSet.HFileOpenSave.filename = os.path.join( BASE_DIR, i.replace('.hwp', 'pdf')) # 확장자는 .pdf로, hwp.HParameterSet.HFileOpenSave.Format = 'PDF' # 포맷은 PDF로,
def find_subHandle(pHandle, winClassList): """ 递归寻找子窗口的句柄 pHandle是祖父窗口的句柄 winClassList是各个子窗口的class列表,父辈的list-index小于子辈 """ assert type(winClassList) == list if len(winClassList) == 1: return find_idxSubHandle(pHandle, winClassList[0][0], winClassList[0][1]) else: pHandle = find_idxSubHandle(pHandle, winClassList[0][0], winClassList[0][1]) return find_subHandle(pHandle, winClassList[1:]) # print win32api.GetCursorPos() # hwnd = win32gui.FindWindow("Qt5QWindowIcon", None) # print ("%x" % (hwnd)) hwnd = win32gui.FindWindow(None, "Wondershare Filmora9") print("%x" % (hwnd)) import time time.sleep(2) handle = win32gui.FindWindowEx(hwnd, None, None, None) print("%x" % (handle)) # editHandle = find_subHandle(hwnd, [("Edit", 0)]) # print ("%x" % (editHandle))
def getPixel(i_x, i_y): # Detect color i_desktop_window_id = win32gui.FindWindow(None, "Minesweeper X") i_desktop_window_dc = win32gui.GetWindowDC(i_desktop_window_id) long_colour = win32gui.GetPixel(i_desktop_window_dc, i_x - winRect[0], i_y - winRect[1]) i_colour = int(long_colour) return ((i_colour & 0xff) << 16) + (i_colour & 0xff00) + ((i_colour & 0xff0000) >> 16)
def run(self): print(self.name + " has started.") while self.__running.isSet(): if self.client_info.getStatusIndex() == ClientStatus.InGame: if win32gui.FindWindow(None, LOL_IN_GAME_CLIENT_NAME) != 0 \ and win32api.GetAsyncKeyState(win32con.VK_TAB): print("tab was pressed") if UserInGameInfo.getInstance().getEnemyInfoArea() is None: self._instance_lock.acquire() # crop the whole image, since we dont know where is the enemy tab_panel = grabImgByRect(self.crop_position, binarize=False) # 把整张图片切成五份, 但是我们不知道左边是敌人还是右边是敌人,所以需要比较一次 teamLeft = cropImgByRect(tab_panel, TEAM_LEFT_IN_TAB) teamRight = cropImgByRect(tab_panel, TEAM_RIGHT_IN_TAB) left_five_imgs = split2NPieces(teamLeft, interval=21, horizontal=False) left_results = ProfileModel.getInstance().predictImgs( left_five_imgs) # right_five_imgs = split2NPieces(teamRight, interval=21, horizontal=False) right_results = ProfileModel.getInstance().predictImgs( right_five_imgs) print("left_results->", left_results) print("right_results->", right_results) # TODO 因为准确率的问题,(不能全部识别对, 所以认对3/5 就算, 实际排位中两方英雄都不一样) if len( set(UserInGameInfo.getInstance(). getEnemyTeamList()).difference( set(right_results))) <= 3: if self.right_twice_flag: UserInGameInfo.getInstance().setEnemyInfoArea( TEAM_RIGHT_IN_TAB) self.right_twice_flag = True elif len( set(UserInGameInfo.getInstance(). getEnemyTeamList()).intersection( set(left_results))) >= 3: if self.left_twice_flag: UserInGameInfo.getInstance().setEnemyInfoArea( TEAM_LEFT_IN_TAB) self.left_twice_flag = True self._instance_lock.release() else: # once we got to know which is enemy, we can only crop small part of pics enemy_panel_area = UserInGameInfo.getInstance( ).getEnemyInfoArea() tab_panel = grabImgByRect(self.crop_position, binarize=False) # 从整张图片提取出来敌人的部分 enemy_info_img = cropImgByRect(tab_panel, enemy_panel_area) # 在这里还需要截自己的装备 self_info_img = None if enemy_panel_area == expandCropArea( TEAM_LEFT_IN_TAB): self_info_img = cropImgByRect( tab_panel, expandCropArea(TEAM_RIGHT_IN_TAB)) else: self_info_img = cropImgByRect( tab_panel, expandCropArea(TEAM_LEFT_IN_TAB)) enemy_info = decodeImgs(enemy_info_img) if len( set(enemy_info.keys()).intersection( set(UserInGameInfo.getInstance(). getEnemyTeamList()))) >= 3: print("enemy_info ->", enemy_info) UserInGameInfo.getInstance().setEnemyInfo( enemy_info) if UserInGameInfo.getInstance().getYourselfChamp( ) is not None: self_team_info = decodeImgs(self_info_img) self_champ = UserInGameInfo.getInstance( ).getYourselfChamp() self_gear = self_team_info.get(self_champ, None) if self_gear is not None: print("self_gear[\"gears\"] ->", self_gear["gears"]) UserInGameInfo.getInstance().setYourselfGears( set(self_gear.get("gears", set())) - set(NONE_LIST)) print( "output gear = ", UserInGameInfo.getInstance(). getYourselfGears()) UserInGameInfo.getInstance( ).setGearDetectedFlag(True) else: # 1. self_champ is wrong # 2. 截取到了地面 pass time.sleep(self._capture_rate)
bufferX = 250 bufferY = 250 centerX = screenWidth / 2 centerY = screenHeight / 2 x1 = centerX - bufferX y1 = centerY - bufferY x2 = centerX + bufferX y2 = centerY + bufferY w = bufferX * 2 h = bufferY * 2 #get window position and info hwnd = win32gui.FindWindow(None, "Overwatch") #hwnd = win32gui.GetDesktopWindow()#for screenshot of entire screen l, t, r, b = win32gui.GetWindowRect(hwnd) windowHeight = b - t windowWidth = r - l windowCenterX = windowWidth / 2 windowCenterY = windowHeight / 2 SSx1 = int(windowCenterX - bufferX) SSy1 = int(windowCenterY - bufferY) SSWidth = bufferX * 2 SSHeight = bufferY * 2 # test really fast screenshots start = time.clock()
def find_window(self, class_name, window_name=None): """Pass a window class name & window name directly if known to get the window """ self._handle = win32gui.FindWindow(class_name, window_name)