所以我有这个代码:
import win32gui
import win32ui
from ctypes import windll
from PIL import Image
hwnd = win32gui.FindWindow(None, "#chat - Discord")
# Change the line below depending on whether you want the whole window
# or just the client area.
left, top, right, bot = win32gui.GetClientRect(hwnd)
#left, top, right, bot = win32gui.GetWindowRect(hwnd)
w = right - left
h = bot - top
hwndDC = win32gui.GetWindowDC(hwnd)
mfcDC = win32ui.CreateDCFromHandle(hwndDC)
saveDC = mfcDC.CreateCompatibleDC()
saveBitMap = win32ui.CreateBitmap()
saveBitMap.CreateCompatibleBitmap(mfcDC, w, h)
saveDC.SelectObject(saveBitMap)
# Change the line below depending on whether you want the whole window
# or just the client area.
result = windll.user32.PrintWindow(hwnd, saveDC.GetSafeHdc(), 1)
#result = windll.user32.PrintWindow(hwnd, saveDC.GetSafeHdc(), 0)
bmpinfo = saveBitMap.GetInfo()
bmpstr = saveBitMap.GetBitmapBits(True)
im = Image.frombuffer(
'RGB',
(bmpinfo['bmWidth'], bmpinfo['bmHeight']),
bmpstr, 'raw', 'BGRX', 0, 1)
if result:
#PrintWindow Succeeded
im.show()
win32gui.DeleteObject(saveBitMap.GetHandle())
saveDC.DeleteDC()
mfcDC.DeleteDC()
win32gui.ReleaseDC(hwnd, hwndDC)
它的问题是它拍摄的屏幕截图全黑。它对所有窗口都这样做,而不仅仅是 Discord。它有什么问题,我需要做什么来修复它?
同样作为一个附带问题 - 当我截取屏幕截图时,命令提示符打开然后快速关闭,有没有办法阻止这种情况发生?
它的问题在于它拍摄的屏幕截图全黑。
我知道你想截图吗?
from PIL.ImageGrab import grab
image = grab()
image.save('Screenshot.png')
如果您有窗口的坐标,请尝试以下操作:
from PIL.ImageGrab import grab
box = (0,0,200,200)
image = grab(box)
image.save('Screenshot.png')
不过,PIL 已停产,因此您可能只能在下一个不久的将来使用此代码。此外,命令提示符不会与此代码一起出现。