Reputation: 255
The following is my code:
import sys
import win32gui
import win32ui
import win32con
from time import sleep
from datetime import datetime
def get_windows_bytitle(title_text):
def _window_callback(hwnd, all_windows):
all_windows.append((hwnd, win32gui.GetWindowText(hwnd)))
windows = []
win32gui.EnumWindows(_window_callback, windows)
return [hwnd for hwnd, title in windows if title_text in title]
def screenshot(hwnd, filename):
l,t,r,b = win32gui.GetClientRect(hwnd)
h = b - t
w = r - l
hDC = win32gui.GetDC(hwnd)
myDC = win32ui.CreateDCFromHandle(hDC)
newDC = myDC.CreateCompatibleDC()
myBitMap = win32ui.CreateBitmap()
myBitMap.CreateCompatibleBitmap(myDC, w, h)
newDC.SelectObject(myBitMap)
win32gui.SetForegroundWindow(hwnd)
sleep(.2) #lame way to allow screen to draw before taking shot
newDC.BitBlt((0,0),(w, h) , myDC, (0,0), win32con.SRCCOPY)
myBitMap.Paint(newDC)
myBitMap.SaveBitmapFile(newDC, "c:\\bla.bmp")
def main():
try:
hwnd = get_windows_bytitle("Chrome")[0]
except IndexError:
print("Chrome window not found")
sys.exit(1)
screenshot(hwnd, str(datetime.now().microsecond) + ".bmp")
if __name__ == "__main__":
main()
It works great on one PC, but running now on my laptop raises the following error for some reason:
win32ui.error: CreateFile
Can't find any info regarding that exception online... For the record (if it makes a difference) I installed the winapi on this laptop using the following package from pypi:
pip install pypiwin32
because installing the regular pywin32 didn't work. Also, now that I think of it, this machine is Windows 8.1 as opposed to Windows 7 on the machine that runs it fine.
Any ideas?
Upvotes: 2
Views: 1980
Reputation: 2984
There must be some permission issue on C:\
and hence it must be failing. Create temp folder (or whatever name you like) and modify your code as shown below
myBitMap.SaveBitmapFile(newDC, "c:\\temp\\bla.bmp")
Note: ensure that temp folder exist.
Upvotes: 2