def current_window_img(offset): window = win32gui.GetActiveWindow() window_rect = win32gui.GetWindowRect(window) target_rect = (window_rect[0] + offset[0], window_rect[1] + offset[1], window_rect[2] + offset[2], window_rect[3] + offset[3]) window_img = ImageGrab.grab(bbox=target_rect) return window_img
def GetWindow(): hwnd = 0 try: hwnd = win32gui.GetActiveWindow() except: hwnd = win32gui.GetForegroundWindow() return hwnd
def IsActive(self): """ Checks to see if the window is the active window :return: True if window is active else False :rtype: bool """ return self.hwnd == win32gui.GetActiveWindow()
def get_target_img(): window = win32gui.GetActiveWindow() rect = win32gui.GetWindowRect(window) rect = (rect[0] + 8, rect[1] + 190, rect[2] - 8, rect[3] - 80) img = ImageGrab.grab(bbox=rect).convert('L') # print("TARGET_IMG: {}".format(img.size)) return img
def checkHealth(keyCode): x, y = calculateHPxy(80) color = win32gui.GetPixel(win32gui.GetDC(win32gui.GetActiveWindow()), x, y) r, g, b = rgbint2rgbtuple(color) if r < 50: time.sleep(0.3) useSkill(keyCode)
def readPixel(x, y): if x >= 1920: x = 1919 if y >= 1080: y = 1079 color = win32gui.GetPixel(win32gui.GetDC(win32gui.GetActiveWindow()), x, y) r, g, b = rgbint2rgbtuple(color) return r, g, b
def get_target_img(): window = win32gui.GetActiveWindow() rect = win32gui.GetWindowRect(window) rect = (rect[0]+8, rect[1]+189, rect[2]-8, rect[3]-80) img = ImageGrab.grab(bbox=rect).convert('L') Image.fromarray(np.uint8(img)).save('test.png') exit() # print("TARGET_IMG: {}".format(img.size)) return img
def checkPartyMemberHealth(autohotpy, x, y): color = win32gui.GetPixel(win32gui.GetDC(win32gui.GetActiveWindow()), x, y) r, g, b = rgbint2rgbtuple(color) if r < 75: print("Party member [{},{}] is at RGB: {}, {}, {}".format( x, y, r, g, b)) click(autohotpy, x, y) keyToPress = getPressByKey(autohotpy, HEAL_PARTY_MEMBER_KEY) keyToPress.press()
def screenShot(self): # 截取游戏图片 win32gui.SetForegroundWindow(self.hwnd) win32gui.GetActiveWindow() x1, y1, x2, y2 = win32gui.GetWindowRect(self.hwnd) # print(x1, y1, x2, y2) self.faker_move_mouse(x2, y2) img_rgb = np.array(ImageGrab.grab((x1, y1, x2, y2))) # img_bgr = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2BGR) # rgb to bgr return img_bgr
def current_window_img(offset): window = win32gui.GetActiveWindow() window_rect = win32gui.GetWindowRect(window) target_rect = (window_rect[0] + offset[0], window_rect[1] + offset[1], window_rect[2] + offset[2], window_rect[3] + offset[3]) window_img = ImageGrab.grab(bbox=target_rect).convert('L') window_img = window_img.resize( (int(window_img.size[0] / 4), int(window_img.size[1] / 4)), Image.BICUBIC) return window_img
def _set_noactivate(self): hwnd = win32gui.GetActiveWindow() current_exstyle = win32gui.GetWindowLong(hwnd, win32con.GWL_EXSTYLE) new_exstyle = ( current_exstyle # | win32con.WS_EX_TOPMOST | win32con.WS_EX_TOOLWINDOW | win32con.WS_EX_NOACTIVATE | win32con.WS_EX_APPWINDOW) win32gui.SetWindowLong(hwnd, win32con.GWL_EXSTYLE, new_exstyle) win32gui.SetWindowPos(hwnd, win32con.HWND_TOPMOST, 0, 0, 0, 0, win32con.SWP_NOMOVE | win32con.SWP_NOSIZE)
def colorPrinter(self): time.sleep(2) while True and self.STOP_THREAD is False: hwnd = win32gui.GetActiveWindow() activeWindow = win32gui.GetDC(hwnd) x, y = win32api.GetCursorPos() color = win32gui.GetPixel(activeWindow, x, y) r, g, b = self.rgbint2rgbtuple(color) state = "[X: {}, Y: {}] -> Color: {} -> RGB : ({}, {}, {})".format( x, y, color, r, g, b) print(state) time.sleep(0.1) win32gui.ReleaseDC(hwnd, activeWindow)
def ShowDialog(parent, manager, config, idd): """Displays another dialog""" if manager.dialog_parser is None: manager.dialog_parser = LoadDialogs() import dialog_map commands = dialog_map.dialog_map[idd] if not parent: import win32gui try: parent = win32gui.GetActiveWindow() except win32gui.error: pass import dlgcore dlg = dlgcore.ProcessorDialog(parent, manager, config, idd, commands) return dlg.DoModal()
def listen_mouse_click(base_window: Window): state_left = win32api.GetKeyState(0x01) dim = base_window.get_dim() while True: a = win32api.GetKeyState(0x01) if a != state_left: # Button state changed state_left = a if a < 0: pass else: flags, hcursor, (x, y) = win32gui.GetCursorInfo() x, y = x - dim['left'], y - dim['top'] pixel = win32gui.GetPixel( win32gui.GetDC(win32gui.GetActiveWindow()), x, y) print(f"({x}, {y}) {hex(pixel)} cell: {xy_to_cell((x, y))}") time.sleep(0.001)
def image_search_all_range( fname, error ): # 이미지 파일, 오차값(이미지 파일의 픽셀값과 화면의 픽셀값을 비교할 때 일치하지 않아도 용납되는 픽셀의 최대 개수. 이미지 파일의 크기가 클 경우 오차값을 크게 하고 작을 경우 작게 설정해야 함) try: im = pilimg.open(fname) # 이미지 파일 정보 저장 pix = np.array(im) # 이미지 파일의 픽셀값 배열로 구성 후 저장 image_size_x = len(pix[0]) - 1 # 이미지 파일의 가로 크기 image_size_y = len(pix) - 1 # 이미지 파일의 세로 크기 windows_pos_x = win32api.GetSystemMetrics( win32con.SM_CXSCREEN) # 화면 가로 크기 windows_pos_y = win32api.GetSystemMetrics( win32con.SM_CYSCREEN) # 화면 세로 크기 match = 0 # 이미지 일치 여부를 판단하는 변수 break_var = 0 # 탈출 변수 # y -> x 순으로 했으므로 설정한 범위 맨 위부터 가로로 서치하면서 내려옴(이미지 서치 시간의 효율성과 관련돼 있음) for w_y in range(0, windows_pos_y): # 화면 세로 크기만큼 반복 for w_x in range(0, windows_pos_x): # 화면 가로 크기만큼 반복 if w_x > windows_pos_x - image_size_x or w_y > windows_pos_y - image_size_y: # 화면 최우측 밑 최하단 처리 break # 범위를 넘어서므로 빠져나감 cur_error = 0 # 현재 이미지 서치 오차값 초기화 for x in range(0, image_size_y): # 이미지 파일의 세로 크기만큼 반복 if break_var == 1: # 탈출 변수 값이 1일 경우 break_var = 0 # 탈출 변수 값 초기화 break # 다음 화면 이미지와의 비교를 위해 빠져나감 for y in range(0, image_size_x): # 이미지 파일의 가로 크기만큼 반복 image_pixel = hex( pix[x][y][0] + pix[x][y][1] * 0x100 + pix[x][y][2] * 0x10000) # 이미지 파일의 픽셀값(1 pixel) 저장 windows_pixel = hex( win32gui.GetPixel( win32gui.GetDC(win32gui.GetActiveWindow()), w_x + x, w_y + y)) # 화면 픽셀값(1 pixel) 저장 if image_pixel == windows_pixel: # 이미지 파일의 픽셀값과 화면의 픽셀값이 같을 경우 match += 1 # 이미지 일치 변수 값 증가 else: # 이미지 파일의 픽셀값과 화면의 픽셀값이 다를 경우 cur_error += 1 # 현재 이미지 서치 오차값 증가 if error < cur_error: # 현재 이미지 서치 오차 값이 설정한 오차값보다 클 경우 break_var = 1 # 탈출 변수 값 설정 break # 이미지 파일의 이미지와 화면의 이미지가 같지 않으므로 빠져나감 if match > image_size_x * image_size_y - error: # 이미지 일치 변수 값이 오차 범위 이내일 경우(이미지 파일의 이미지와 화면의 이미지가 비슷한 경우) return True # 이미지 서치가 성공했을 경우의 반환 match = 0 # 이미지 일치 변수 값 초기화 return False # 이미지 서치가 실패했을 경우의 반환 except Exception as e: return False # 이미지 서치가 실패했을 경우의 반환
def image_search_particular_range( fname, start_pos_x, start_pos_y, end_pos_x, end_pos_y, error ): # 이미지 파일, 서치 시작 x좌표, 서치 시작 y좌표, 서치 마지막 x좌표, 서치 마지막 y좌표, 오차값(이미지 파일의 픽셀값과 화면의 픽셀값을 비교할 때 일치하지 않아도 용납되는 픽셀의 최대 개수. 이미지 파일의 크기가 클 경우 오차값을 크게 하고 작을 경우 작게 설정해야 함) try: im = pilimg.open(fname) # 이미지 파일 정보 저장 pix = np.array(im) # 이미지 파일의 픽셀값 배열로 구성 후 저장 image_size_x = len(pix[0]) - 1 # 이미지 파일의 가로 크기 image_size_y = len(pix) - 1 # 이미지 파일의 세로 크기 match = 0 # 이미지 일치 여부를 판단하는 변수 break_var = 0 # 탈출 변수 if end_pos_x - start_pos_x < image_size_x or end_pos_y - start_pos_y < image_size_y: # 설정한 범위가 이미지 파일 크기보다 작을 경우 print('[-] 설정한 범위가 이미지 파일 크기보다 작습니다.') return False # 이미지 서치가 실패했을 경우의 반환 # y -> x 순으로 했으므로 설정한 범위 맨 위부터 가로로 서치하면서 내려옴(이미지 서치 시간의 효율성과 관련돼 있음) for w_y in range(start_pos_y, end_pos_y): # 설정한 세로 범위만큼 반복 for w_x in range(start_pos_x, end_pos_x): # 설정한 가로 범위만큼 반복 if w_x > end_pos_x - image_size_x or w_y > end_pos_y - image_size_y: # 화면 최우측 밑 최하단 처리 break # 범위를 넘어서므로 빠져나감 cur_error = 0 # 현재 이미지 서치 오차값 초기화 for x in range(0, image_size_y): # 이미지 파일의 세로 크기만큼 반복 if break_var == 1: # 탈출 변수 값이 1일 경우 break_var = 0 # 탈출 변수 값 초기화 break # 다음 화면 이미지와의 비교를 위해 빠져나감 for y in range(0, image_size_x): # 이미지 파일의 가로 크기만큼 반복 image_pixel = hex( pix[x][y][0] + pix[x][y][1] * 0x100 + pix[x][y][2] * 0x10000) # 이미지 파일의 픽셀값(1 pixel) 저장 windows_pixel = hex( win32gui.GetPixel( win32gui.GetDC(win32gui.GetActiveWindow()), w_x + x, w_y + y)) # 화면 픽셀값(1 pixel) 저장 if image_pixel == windows_pixel: # 이미지 파일의 픽셀값과 화면의 픽셀값이 같을 경우 match += 1 # 이미지 일치 변수 값 증가 else: # 이미지 파일의 픽셀값과 화면의 픽셀값이 다를 경우 cur_error += 1 # 현재 이미지 서치 오차값 증가 if error < cur_error: # 현재 이미지 서치 오차값이 설정한 오차값보다 클 경우 break_var = 1 # 탈출 변수 값 설정 break # 이미지 파일의 이미지와 화면의 이미지가 같지 않으므로 빠져나감 if match > image_size_x * image_size_y - error: # 이미지 일치 변수 값이 오차 범위 이내일 경우(이미지 파일의 이미지와 화면의 이미지가 비슷한 경우) return True # 이미지 서치가 성공했을 경우의 반환 match = 0 # 이미지 일치 변수 값 초기화 return False # 이미지 서치가 실패했을 경우의 반환 except Exception as e: return False # 이미지 서치가 실패했을 경우의 반환
def image_search_particular_range_fast_thread( pix, image_size_x, image_size_y, w_y, start_pos_x, start_pos_y, end_pos_x, end_pos_y, pixel_count, sem, error): # 화면 특정 범위를 대상으로 이미지 서치하는 함수 스레드 try: sem.acquire() # 임계영역 생성 match = 0 # 이미지 일치 여부를 판단하는 변수 for w_x in range(start_pos_x, end_pos_x): # 설정한 가로 범위만큼 반복 if w_x > end_pos_x - image_size_x or w_y > end_pos_y - image_size_y: # 화면 최우측 밑 최하단 처리 break # 범위를 넘어서므로 빠져나감 cur_error = 0 # 현재 이미지 서치 오차값 초기화 for i in range(0, pixel_count): # 설정한 비교할 픽셀의 개수만큼 반복 random_pixel_x = random.randrange(0, image_size_y + 1) # 이미지 파일 가로 크기 내의 랜덤한 값 random_pixel_y = random.randrange(0, image_size_x + 1) # 이미지 파일 세로 크기 내의 랜덤한 값 image_pixel = hex( pix[random_pixel_x][random_pixel_y][0] + pix[random_pixel_x][random_pixel_y][1] * 0x100 + pix[random_pixel_x][random_pixel_y][2] * 0x10000) # 랜덤한 위치의 이미지 파일의 픽셀값(1 pixel) 저장 windows_pixel = hex( win32gui.GetPixel( win32gui.GetDC(win32gui.GetActiveWindow()), w_x + random_pixel_x, w_y + random_pixel_y)) # 화면 픽셀값(1 pixel) 저장 if image_pixel == windows_pixel: # 이미지 파일의 픽셀값과 화면의 픽셀값이 같을 경우 match += 1 # 이미지 일치 변수 값 증가 else: # 이미지 파일의 픽셀값과 화면의 픽셀값이 다를 경우 cur_error += 1 # 현재 이미지 서치 오차값 증가 if error < cur_error: # 현재 이미지 서치 오차값이 설정한 오차값보다 클 경우 break # 이미지 파일의 이미지와 화면의 이미지가 같지 않으므로 빠져나감 if match > pixel_count - error: # 이미지 일치 변수 값이 오차 범위 이내일 경우(이미지 파일의 이미지와 화면의 이미지가 비슷한 경우) ########################## 이미지 서치 성공했을 경우의 작업 추가 ########################## sem.release() # 임계영역 해제 return match = 0 # 이미지 일치 변수 값 초기화 sem.release() # 임계영역 해제 except Exception as e: sem.release() # 임계영역 해제 pass
def getScreenShot(x1, y1, x2, y2, filename): w = x2 - x1 h = y2 - y1 hwnd = win32gui.GetActiveWindow() hwnd = win32gui.FindWindow(None, "Rise Online Client") # hwnd = win32gui.FindWindow(None, anyOtpTitle) wDC = win32gui.GetWindowDC(hwnd) dcObj = win32ui.CreateDCFromHandle(wDC) cDC = dcObj.CreateCompatibleDC() dataBitMap = win32ui.CreateBitmap() dataBitMap.CreateCompatibleBitmap(dcObj, w, h) cDC.SelectObject(dataBitMap) cDC.BitBlt((0, 0), (w, h), dcObj, (x1, y1), win32con.SRCCOPY) dataBitMap.SaveBitmapFile(cDC, filename + ".png") # Data version of png file # signedIntsArray = dataBitMap.GetBitmapBits(True) # img = np.fromstring(signedIntsArray, dtype='uint8') # cv2.imshow(img) # Free Resources dcObj.DeleteDC() cDC.DeleteDC() win32gui.ReleaseDC(hwnd, wDC) win32gui.DeleteObject(dataBitMap.GetHandle())
def get_cursor_pos_color(x=None, y=None, **ka): ''' x or y arg 优先 return [x,y],color ''' U, T, N, F = py.importUTNF() if not py.isint(x) and y == None: pos = x if x == None or y == None: pos = U.get_duplicated_kargs(ka, 'pos', 'xy') if not pos: pos = get_cursor_pos() else: pos = [x, y] pos = py.list(pos) if py.isint(x): pos[0] = x if py.isint(y): pos[1] = y import win32gui color = win32gui.GetPixel(win32gui.GetDC(win32gui.GetActiveWindow()), *pos) if color < 256: color = 256 * 256 * color color = U.IntCustomRepr(color, repr=U.rgb_name(color)) return pos, color
def create_map(): map = [] dic = {} #line = colomne et vice versa for colomn in range(nby): map.append([]) for line in range(nbx): pixel = win32gui.GetPixel(win32gui.GetDC(win32gui.GetActiveWindow()),\ POS0[0] + size*line + size * (colomn%2) // 2,\ POS0[1] + colomn * size // 4) pixel = (pixel & 255, (pixel >> 8) & 255, (pixel >> 16) & 255) dic[pixel] = dic.get(pixel, 1) + 1 if pixel == (0, 0, 0): map[colomn].append(trou) elif pixel == (150, 142, 103) or pixel == (142, 134, 94): map[colomn].append(case) elif pixel == (88, 83, 58): map[colomn].append(monte) else: move_to((POS0[0] + size*line + size * (colomn%2) // 2,\ POS0[1] + colomn * size // 4)) time.sleep(2) return dic, map
def get_color(location): x, y = location return hex(win32gui.GetPixel(win32gui.GetDC(win32gui.GetActiveWindow()), x, y))
def ftClick(): print("Record click x,y") time.sleep(5) x, y = win32api.GetCursorPos() print("Record color x,y") time.sleep(5) checkX, checkY = win32api.GetCursorPos() print("Record 2nd color x,y") time.sleep(5) checkX2, checkY2 = win32api.GetCursorPos() print("starting in 5...") time.sleep(5) print(x) print(y) x2 = 1083 y2 = 587 commandListenerThread = threading.Thread(target=screenOnClickListenThread) commandListenerThread.daemon = True commandListenerThread.start() forgottenX = 1073 forgottenY = 587 confirmX = 1071 confirmY = 587 while True: activeWindow = win32gui.GetDC(win32gui.GetActiveWindow()) print(win32gui.GetWindowText(win32gui.GetForegroundWindow())) if win32gui.GetWindowText( win32gui.GetForegroundWindow()) == "Rise Online Client": # color = win32gui.GetPixel(activeWindow, x, y) # r, g, b = rgbint2rgbtuple(color) greenCounter = 0 for index in range(6): color = win32gui.GetPixel(activeWindow, checkX + index, checkY) g = (color >> 8) & 255 if g > 100: greenCounter = greenCounter + 1 for index in range(6): color = win32gui.GetPixel(activeWindow, checkX2 + index, checkY2) g = (color >> 8) & 255 if g > 100: greenCounter = greenCounter + 1 print("GreenCounter: ", greenCounter) if greenCounter > 4: print("CLICK") click(x, y) rightClick(x, y) else: print("RIGHT") useSkill(KEY_B) time.sleep(0.05) rightClick(x, y) else: time.sleep(2)
import win32gui import win32api from colorlist import * import tkinter, win32api, win32con, pywintypes import os import time from threading import Thread hwnd = win32gui.GetDC(win32gui.GetActiveWindow()) def fillall(color): colorx = win32api.RGB(color[0], color[1], color[2]) for x in range(0, 1919): # fill all display for y in range(0, 1079): win32gui.SetPixel(hwnd, x, y, colorx) def draw(x, y, x2, y2, color): colorx = win32api.RGB(color[0], color[1], color[2]) # fill area from point to point for i in range(x, x2): for j in range(y, y2): win32gui.SetPixel(hwnd, i, j, colorx) def d(x, y, lenx, color, step, d): colorx = win32api.RGB(color[0], color[1], color[2]) if d == "rl": for b in range(lenx): win32gui.SetPixel( hwnd, x, y, colorx
parser.add_argument("window", help="name of the program you want to run in", type=str) parser.add_argument("command", help="functionality you want to execute", type=str) parser.add_argument("--repeat", help="nuber of times you wand command to be repeated", default=1, type=int) parser.add_argument("--params", nargs='*', default=[]) args = parser.parse_args() windowName = args.window winId = SimpleWindowCheck(windowName) activeWindow = win32gui.GetActiveWindow() if not (winId): windowList = [] def enumHandler(hwnd, list): if windowName in win32gui.GetWindowText(hwnd): list.append(hwnd) win32gui.EnumWindows(enumHandler, windowList) # only the first id, may need to try the others winId = windowList[0] # can check with this for hwnd in windowList: hwndChild = win32gui.GetWindow(hwnd, win32con.GW_CHILD)
def get_active_window(): """Within current thread @return HWND or ? """ return win32gui.GetActiveWindow()
def GetWinHWND(): global Win_hwnd Win_hwnd = win32gui.GetActiveWindow()
def pixelAt(x, y): """Return a pixel color at (x, y) --> Hex""" return hex( win32gui.GetPixel(win32gui.GetDC(win32gui.GetActiveWindow()), x, y))
def GetActiveWindow(self): '''I seem to have problems with this when it is run in a dos window?''' return (cWindow(win32gui.GetActiveWindow()))
def get_active_window(self): return win32gui.GetActiveWindow()
def get_color(location): # 좌표를 구합니다. x, y = location # win32gui모듈로 색상값을 따 오고, 16진수로 변환하여 리턴합니다. return hex(win32gui.GetPixel(win32gui.GetDC(win32gui.GetActiveWindow()), x, y))