import win32api, win32con, time, cv2,win32gui,os,sys,numpy as np,win32ui
from PIL import Image, ImageGrab
BASE_DIR=os.path.dirname(os.path.abspath(__file__))
sys.path.append(BASE_DIR)
import lunia.pictool as lp, lunia.constant as lc,lunia.luniatool as lt,lunia.numberpictool as ln
class LuniaGameWindows:
def __init__(self):
self.windowTitle = lc.gameWindowTitle
self.wds=[]
self.wdposes=[]
win32gui.EnumWindows(self.findLuniaWindows, 0)
self.sortWindows()
def findLuniaWindows(self,x,mouse):
if win32gui.GetWindowText(x)==self.windowTitle:
self.wds.append(x)
self.wdposes.append(win32gui.GetWindowRect(x))
def captureWindow(self,i,offset1=None,offset2=None,doActive=False,use_offset=True):
if doActive:
time.sleep(.5)
win32gui.SetForegroundWindow(self.wds[i])
time.sleep(1)
if use_offset:
return self.capture(*self.calculatePos(i,offset1),*self.calculatePos(i,offset2))
else:
return self.capture(*offset1, *offset2)
def capture(self,x1, y1, x2, y2):
img = ImageGrab.grab((x1, y1, x2, y2))
return img
def calculatePos(self,i,offset):
return self.wdposes[i][0] + offset[0], self.wdposes[i][1] + offset[1]
def sortWindows(self):
self.wds=[x for y, x in sorted(zip(self.wdposes,self.wds),key=lambda x:x[0][0])]
self.wdposes=sorted(self.wdposes,key=lambda x:x[0])
print('窗口句柄是{}'.format(self.wds))
print('窗口坐标是{}'.format(self.wdposes))
def doClick(self,hwnd,cx, cy):
time.sleep(1)
print(hwnd,cx, cy)
pos = win32api.MAKELONG(cx, cy)
time.sleep(2)
i=win32con.VK_ESCAPE
i=98
win32api.PostMessage(hwnd, win32con.WM_RBUTTONDOWN, 0,0)
win32api.PostMessage(hwnd, win32con.WM_RBUTTONUP, 0,0)
time.sleep(2)
win32api.PostMessage(hwnd, win32con.WM_KEYDOWN,i,0)
win32api.PostMessage(hwnd, win32con.WM_KEYUP, i, 0)
def capture_background(self,i):
hWnd=self.wds[i]
left, top, right, bot = self.wdposes[i]
width = right - left
height = bot - top
hWndDC = win32gui.GetWindowDC(hWnd)
mfcDC = win32ui.CreateDCFromHandle(hWndDC)
saveDC = mfcDC.CreateCompatibleDC()
saveBitMap = win32ui.CreateBitmap()
saveBitMap.CreateCompatibleBitmap(mfcDC, width, height)
saveDC.SelectObject(saveBitMap)
saveDC.BitBlt((0, 0), (width, height), mfcDC, (0, 0), win32con.SRCCOPY)
bmpinfo = saveBitMap.GetInfo()
bmpstr = saveBitMap.GetBitmapBits(True)
im_PIL = Image.frombuffer('RGB', (bmpinfo['bmWidth'], bmpinfo['bmHeight']), bmpstr, 'raw', 'BGRX', 0, 1)
win32gui.DeleteObject(saveBitMap.GetHandle())
saveDC.DeleteDC()
mfcDC.DeleteDC()
win32gui.ReleaseDC(hWnd, hWndDC)
im_PIL.show()
if __name__=='__main__':
lgw=LuniaGameWindows()
i=-1
hwnd=lgw.wds[i]
lgw.capture_background(-1)