python 自动化

 

import pyautogui
import time
from ctypes import windll, byref
from ctypes.wintypes import HWND
import string
from ctypes.wintypes import HWND, POINT

PostMessageW = windll.user32.PostMessageW
ClientToScreen = windll.user32.ClientToScreen
MapVirtualKeyW = windll.user32.MapVirtualKeyW
VkKeyScanA = windll.user32.VkKeyScanA

WM_KEYDOWN = 0x100
WM_KEYUP = 0x101


WM_MOUSEMOVE = 0x0200
WM_LBUTTONDOWN = 0x0201
WM_LBUTTONUP = 0x202
WM_MOUSEWHEEL = 0x020A
WHEEL_DELTA = 120

print(pyautogui.size())
print(pyautogui.position())
print(pyautogui.onScreen(192,180))

screenWidth,screenHeight = pyautogui.size() # 获取屏幕分辨率
pyautogui.moveTo(screenWidth / 2,screenHeight / 2)# 鼠标移动到 屏幕中心
currentMouseX,currentMouseY = pyautogui.position() # 获取鼠标位置
print(currentMouseX,currentMouseY) # 打印鼠标位置 输出 屏幕中心值

# pyautogui.dragTo(100,200,button='left')
# pyautogui.typewrite('Hello world!') # 输入Hello world!
# pyautogui.press('option') # 按一下键盘Esc键

# time.sleep(1)
# pyautogui.hotkey('winleft','d')
# time.sleep(1)
# print(pyautogui.locateCenterOnScreen('d:\\aa.png'))

  

#对后台窗口截图
import win32gui, win32ui, win32con
from ctypes import windll
from PIL import Image
import cv2
import numpy
# https://www.cnblogs.com/enumx/p/12337132.html
#获取后台窗口的句柄,注意后台窗口不能最小化
hWnd = win32gui.FindWindow(None, "小森生活 - MuMu模拟器")
#获取句柄窗口的大小信息
left, top, right, bot = win32gui.GetWindowRect(hWnd)
width = right - left
height = bot - top
#返回句柄窗口的设备环境,覆盖整个窗口,包括非客户区,标题栏,菜单,边框
hWndDC = win32gui.GetWindowDC(hWnd)
#创建设备描述表
mfcDC = win32ui.CreateDCFromHandle(hWndDC)
#创建内存设备描述表
saveDC = mfcDC.CreateCompatibleDC()
#创建位图对象准备保存图片
saveBitMap = win32ui.CreateBitmap()
#为bitmap开辟存储空间
saveBitMap.CreateCompatibleBitmap(mfcDC,width,height)
#将截图保存到saveBitMap中
saveDC.SelectObject(saveBitMap)
#保存bitmap到内存设备描述表
saveDC.BitBlt((0,0), (width,height), mfcDC, (0, 0), win32con.SRCCOPY)
 
#如果要截图到打印设备:
###最后一个int参数:0-保存整个窗口,1-只保存客户区。如果PrintWindow成功函数返回值为1
#result = windll.user32.PrintWindow(hWnd,saveDC.GetSafeHdc(),0)
#print(result) #PrintWindow成功则输出1
 
#保存图像
##方法一:windows api保存
###保存bitmap到文件
str_time_now = time.strftime("%Y-%m-%d_%H_%M_%S", time.localtime())
imgpath = "d:\\img_Winapi" + str_time_now + ".bmp"
saveBitMap.SaveBitmapFile(saveDC,"d:\\img_Winapi" + str_time_now + ".bmp")
print(print(pyautogui.size()))
win32gui.DeleteObject(saveBitMap.GetHandle())
saveDC.DeleteDC()
mfcDC.DeleteDC()
win32gui.ReleaseDC(hWnd,hWndDC)

 

# https://docs.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes
VkCode = {
    "back":  0x08,
    "tab":  0x09,
    "return":  0x0D,
    "shift":  0x10,
    "control":  0x11,
    "menu":  0x12,
    "pause":  0x13,
    "capital":  0x14,
    "escape":  0x1B,
    "space":  0x20,
    "end":  0x23,
    "home":  0x24,
    "left":  0x25,
    "up":  0x26,
    "right":  0x27,
    "down":  0x28,
    "print":  0x2A,
    "snapshot":  0x2C,
    "insert":  0x2D,
    "delete":  0x2E,
    "lwin":  0x5B,
    "rwin":  0x5C,
    "numpad0":  0x60,
    "numpad1":  0x61,
    "numpad2":  0x62,
    "numpad3":  0x63,
    "numpad4":  0x64,
    "numpad5":  0x65,
    "numpad6":  0x66,
    "numpad7":  0x67,
    "numpad8":  0x68,
    "numpad9":  0x69,
    "multiply":  0x6A,
    "add":  0x6B,
    "separator":  0x6C,
    "subtract":  0x6D,
    "decimal":  0x6E,
    "divide":  0x6F,
    "f1":  0x70,
    "f2":  0x71,
    "f3":  0x72,
    "f4":  0x73,
    "f5":  0x74,
    "f6":  0x75,
    "f7":  0x76,
    "f8":  0x77,
    "f9":  0x78,
    "f10":  0x79,
    "f11":  0x7A,
    "f12":  0x7B,
    "numlock":  0x90,
    "scroll":  0x91,
    "lshift":  0xA0,
    "rshift":  0xA1,
    "lcontrol":  0xA2,
    "rcontrol":  0xA3,
    "lmenu":  0xA4,
    "rmenu":  0XA5
}


def get_virtual_keycode(key: str):
    if len(key) == 1 and key in string.printable:
        # https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-vkkeyscana
        return VkKeyScanA(ord(key)) & 0xff
    else:
        return VkCode[key]

def key_down(handle: HWND, key: str):
    """
    Args:
        handle (HWND): 窗口句柄
        key (str): 按键名
    """
    vk_code = get_virtual_keycode(key)
    scan_code = MapVirtualKeyW(vk_code, 0)
    # https://docs.microsoft.com/en-us/windows/win32/inputdev/wm-keydown
    wparam = vk_code
    lparam = (scan_code << 16) | 1
    PostMessageW(handle, WM_KEYDOWN, wparam, lparam)

def key_up(handle: HWND, key: str):
    """放开指定按键
    Args:
        handle (HWND): 窗口句柄
        key (str): 按键名
    """
    vk_code = get_virtual_keycode(key)
    scan_code = MapVirtualKeyW(vk_code, 0)
    # https://docs.microsoft.com/en-us/windows/win32/inputdev/wm-keyup
    wparam = vk_code
    lparam = (scan_code << 16) | 0XC0000001
    PostMessageW(handle, WM_KEYUP, wparam, lparam)
    

  

import win32gui
import win32api
import win32con
import time

#https://github.com/neal365/python/blob/master/mouseClick.py
#https://www.programcreek.com/python/example/104592/win32api.mouse_event
def LeftClick(handle, x: int, y: int):
    # client_pos = win32gui.ScreenToClient(handle, (x,y))
    tmp = win32api.MAKELONG(x, y)
    win32gui.SendMessage(handle, win32con.WM_ACTIVATE, win32con.WA_ACTIVE, 0)
    win32api.SendMessage(handle, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, tmp) 
    win32api.SendMessage(handle, win32con.WM_LBUTTONUP, win32con.MK_LBUTTON, tmp)    

def RightClick(handle, x: int, y: int):
    # client_pos = win32gui.ScreenToClient(handle, (x,y))
    tmp = win32api.MAKELONG(x, y)
    win32gui.SendMessage(handle, win32con.WM_ACTIVATE, win32con.WA_ACTIVE, 0)
    win32api.SendMessage(handle, win32con.WM_RBUTTONDOWN, win32con.MK_RBUTTON, tmp) 
    win32api.SendMessage(handle, win32con.WM_RBUTTONUP, win32con.MK_RBUTTON, tmp)

def DragTo(handle, deltaX, deltaY):
    x1,y1 = get_curpos()
    x2,y2 = x1 + deltaX, y1 + deltaY
    print(x1,y1, x2,y2)
    win32gui.SendMessage(handle, win32con.WM_LBUTTONDOWN,  win32con.MK_LBUTTON, win32api.MAKELONG(x1, y1))
    time.sleep(200 / 1000)
    win32gui.SendMessage(handle, win32con.WM_MOUSEMOVE, win32con.MK_LBUTTON, win32api.MAKELONG(x2, y2))
    time.sleep(20 / 1000)
    win32api.SetCursorPos((x2, y2))
    win32gui.SendMessage(handle, win32con.WM_LBUTTONUP, win32con.MK_LBUTTON, win32api.MAKELONG(x2, y2))
           
def get_curpos():
    return win32gui.GetCursorPos()

def get_win_handle(x,y):
    return win32gui.WindowFromPoint((x, y))

#-------------
def LeftDown():
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0) 

def LeftUp():
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0)

def RightDown():
    win32api.mouse_event(win32con.MOUSEEVENTF_RIGHTDOWN, 0, 0) 

def RightUp():
    win32api.mouse_event(win32con.MOUSEEVENTF_RIGHTUP, 0, 0) 

  

def findImg(source, target):
    import cv2
    import numpy as np
    image= cv2.imread('d:\\222.png')
    cv2.imshow('222', image)
    # cv2.waitKey(0)
    gray= cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    template= cv2.imread('d:\\img_Winapi2023-03-06_09_54_37.bmp',0)
    result= cv2.matchTemplate(gray, template, cv2.TM_CCOEFF)
    min_val, max_val, min_loc, max_loc= cv2.minMaxLoc(result)
    height, width= template.shape[:2]

    top_left= max_loc
    bottom_right= (top_left[0] + width, top_left[1] + height)
    cv2.rectangle(image, top_left, bottom_right, (0,0,255),5)

    # cv2.imshow('222', image)
    # cv2.waitKey(0)
    cv2.destroyAllWindows()
    # print(result)
    # print(top_left)
    return top_left

pos = findImg('','')
pyautogui.leftClick(x=pos[0]+2, y=pos[1]+2, interval=0.0, duration=0.21)

  

 

handle = windll.user32.FindWindowW(None, "小森生活 - MuMu模拟器")
import sys
if not windll.shell32.IsUserAnAdmin():
    # 不是管理员就提权
    windll.shell32.ShellExecuteW(
        None, "runas", sys.executable, __file__, None, 1)
import cv2
# 点击线路
left_down(handle, 1234, 20)
time.sleep(2)
left_up(handle, 1234, 20)
time.sleep(1)
# 滚动线路列表
scroll_down(handle, 1000, 200)

 

# 生成验证码
# pip install captcha
from captcha.image import ImageCaptcha
import os
image = ImageCaptcha(width=width, height=height, font_sizes=(int(height * 0.9), int(height * 0.85)))
text = "abcd"
file = os.path.join("d:\\", f"{text}.png")
file = os.path.normpath(file)
image.write(text, file)

  

handle = windll.user32.FindWindowW(None, "小森生活 - MuMu模拟器")
print(handle)
key_down(handle, 'w')
time.sleep(6)
key_up(handle, 'w')
key_down(handle, 'a')
time.sleep(6)
key_up(handle, 'a')

pyautogui.leftClick(x=1300, y=100, interval=0.0, duration=0.21) #open map
time.sleep(1)
pyautogui.leftClick(x=800, y=130, interval=0.0, duration=0.31)
#pyautogui.mouseDown(x=1300, y=100, button='primary', duration=0.1,)
#pyautogui.mouseUp(x=1300, y=100, button='primary', duration=0.0,)

  

 

 

 

 

 

 

 

posted @ 2023-03-06 16:32  zyip  阅读(221)  评论(0)    收藏  举报