python基于win32實現(xiàn)窗口截圖
本文實例為大家分享了python基于win32實現(xiàn)窗口截圖的具體代碼,供大家參考,具體內(nèi)容如下
獲取窗口句柄和標(biāo)題
import win32guihwnd_title = dict()def _get_all_hwnd(hwnd, mouse): if win32gui.IsWindow(hwnd) and win32gui.IsWindowEnabled(hwnd) and win32gui.IsWindowVisible(hwnd): hwnd_title.update({hwnd: win32gui.GetWindowText(hwnd)})win32gui.EnumWindows(_get_all_hwnd, 0)for wnd in hwnd_title.items(): print(wnd)
運行結(jié)果如下,格式為:(窗口句柄, 窗口標(biāo)題)可自行根據(jù)標(biāo)題篩選想要的窗口
(65772, ’’)(262798, ’pythonProject ? screenShot.py’)(5114244, ’項目里程碑.ppt[兼容模式] - PowerPoint’)(3803304, ’’)(133646, ’’)(133642, ’’)
根據(jù)窗口句柄截圖
import win32com.clientimport win32guiimport win32apiimport win32conimport win32uifrom PIL import Imagedef setForeground(hwnd): ''' 將窗口設(shè)置為最前面 :param hwnd: 窗口句柄 一個整數(shù) ''' if hwnd != win32gui.GetForegroundWindow(): shell = win32com.client.Dispatch('WScript.Shell') shell.SendKeys(’%’) win32gui.SetForegroundWindow(hwnd)def winShot(hwnd): ''' 根據(jù)窗口句柄截取窗口視圖 :param hwnd: 窗口句柄 一個整數(shù) ''' bmpFileName = ’screenshot.bmp’ jpgFileName = ’screenshot.jpg’ r = win32gui.GetWindowRect(hwnd) hwin = win32gui.GetDesktopWindow() # 圖片最左邊距離主屏左上角的水平距離 left = win32api.GetSystemMetrics(win32con.SM_XVIRTUALSCREEN) # 圖片最上邊距離主屏左上角的垂直距離 top = win32api.GetSystemMetrics(win32con.SM_YVIRTUALSCREEN) hwindc = win32gui.GetWindowDC(hwin) srcdc = win32ui.CreateDCFromHandle(hwindc) memdc = srcdc.CreateCompatibleDC() bmp = win32ui.CreateBitmap() bmp.CreateCompatibleBitmap(srcdc, r[2] - r[0], r[3] - r[1]) memdc.SelectObject(bmp) memdc.BitBlt((-r[0], top - r[1]), (r[2], r[3] - top), srcdc, (left, top), win32con.SRCCOPY) bmp.SaveBitmapFile(memdc, bmpFileName) im = Image.open(bmpFileName) im = im.convert(’RGB’) im.save(jpgFileName)if __name__ == ’__main__’: setForeground(5114244) winShot(5114244)
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. python爬蟲beautifulsoup解析html方法2. Python 如何將integer轉(zhuǎn)化為羅馬數(shù)(3999以內(nèi))3. python 實現(xiàn)aes256加密4. 詳解Python模塊化編程與裝飾器5. css進(jìn)階學(xué)習(xí) 選擇符6. Python性能測試工具Locust安裝及使用7. 以PHP代碼為實例詳解RabbitMQ消息隊列中間件的6種模式8. 使用Python解析Chrome瀏覽器書簽的示例9. html小技巧之td,div標(biāo)簽里內(nèi)容不換行10. python web框架的總結(jié)
