python - 收到 win32ui.error : CreateFile when trying to save a screenshot with python and winapi

标签 python winapi pywin32

以下是我的代码:

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()

它在一台 PC 上运行良好,但现在在我的笔记本电脑上运行时由于某种原因会引发以下错误:

win32ui.error: CreateFile

无法在网上找到有关该异常的任何信息...为了记录(如果有影响的话),我使用 pypi 中的以下软件包在这台笔记本电脑上安装了 winapi:

pip install pypiwin32

因为安装常规的 pywin32 不起作用。 另外,现在我想起来了,这台机器是 Windows 8.1,而不是运行良好的机器上的 Windows 7。

有什么想法吗?

最佳答案

C:\ 上一定存在一些权限问题,因此它一定会失败。创建临时文件夹(或任何您喜欢的名称)并修改您的代码,如下所示

myBitMap.SaveBitmapFile(newDC, "c:\\temp\\bla.bmp")

注意:确保临时文件夹存在。

关于python - 收到 win32ui.error : CreateFile when trying to save a screenshot with python and winapi,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28526827/

相关文章:

C++:通过进程ID、进程句柄和标题名称从进程中获取唯一窗口的窗口句柄的最佳方法

c++ - 我可以允许多个程序同时读取同一个文件吗?

python - 从另一个应用程序的表单/字段获取文本

python - 如何在 python 中使用 espeak 演奏动态弦乐

windows - 最小的 Windows (PE) 可执行文件是什么?

php - 无法确定 laravel 文件路径

python - 如何增加Windows上气球弹出通知的时间

python - 仅镜像屏幕旋转 - Python

python - 有没有办法在 Python 中编辑包含图像的 xlsx 工作簿?

Python/Arduino : PySerial, Matplotlib,numpy;树莓派