前提:使用電子應用程序,QT,WPF ...等框架制作的應用程序將響應GetDC
或打印黑屏GetWindowDC
。解決此問題的唯一方法是確保目標應用程序可見,並在目標應用程序所在的特定坐標處為桌面截圖
C++代碼:
#include <fstream> #include <vector> #include <windows.h> int main() { //make sure process is DPI aware SetProcessDPIAware(); HWND hwnd_target = FindWindowA("Notepad", NULL); if(!hwnd_target) return 0; //make sure target window is on top SetForegroundWindow(hwnd_target); Sleep(250); //get hdc of desktop HDC hdc = GetDC(HWND_DESKTOP); //copy bits from coordinates of target window RECT rc; GetWindowRect(hwnd_target, &rc); int w = rc.right - rc.left; int h = rc.bottom - rc.top; HDC memdc = CreateCompatibleDC(hdc); HBITMAP hbitmap = CreateCompatibleBitmap(hdc, w, h); HGDIOBJ oldbmp = SelectObject(memdc, hbitmap); BitBlt(memdc, 0, 0, w, h, hdc, rc.left, rc.top, SRCCOPY | CAPTUREBLT); SelectObject(memdc, oldbmp); DeleteDC(memdc); //restore the foreground SetForegroundWindow(GetConsoleWindow()); //save to file BITMAPINFOHEADER bi = { sizeof(bi), w, h, 1, 32 }; std::vector<BYTE> pixels(w * h * 4); GetDIBits(hdc, hbitmap, 0, h, pixels.data(), (BITMAPINFO*)&bi, DIB_RGB_COLORS); std::ofstream fout("filename.bmp", std::ios::binary); BITMAPFILEHEADER hdr = { 'MB', 54 + bi.biSizeImage, 0, 0, 54 }; fout.write((char*)&hdr, 14); fout.write((char*)&bi, 40); fout.write((char*)pixels.data(), pixels.size()); DeleteObject(hbitmap); ReleaseDC(HWND_DESKTOP, hdc); return 0; }
python代碼:
import win32gui import win32ui import win32con from ctypes import windll from PIL import Image import time import ctypes hwnd_target = win32gui.FindWindow(None, 'Calculator') #Chrome handle be used for test left, top, right, bot = win32gui.GetWindowRect(hwnd_target) w = right - left h = bot - top win32gui.SetForegroundWindow(hwnd_target) time.sleep(1.0) hdesktop = win32gui.GetDesktopWindow() hwndDC = win32gui.GetWindowDC(hdesktop) mfcDC = win32ui.CreateDCFromHandle(hwndDC) saveDC = mfcDC.CreateCompatibleDC() saveBitMap = win32ui.CreateBitmap() saveBitMap.CreateCompatibleBitmap(mfcDC, w, h) saveDC.SelectObject(saveBitMap) result = saveDC.BitBlt((0, 0), (w, h), mfcDC, (left, top), win32con.SRCCOPY) bmpinfo = saveBitMap.GetInfo() bmpstr = saveBitMap.GetBitmapBits(True) im = Image.frombuffer( 'RGB', (bmpinfo['bmWidth'], bmpinfo['bmHeight']), bmpstr, 'raw', 'BGRX', 0, 1) win32gui.DeleteObject(saveBitMap.GetHandle()) saveDC.DeleteDC() mfcDC.DeleteDC() win32gui.ReleaseDC(hdesktop, hwndDC) if result == None: #PrintWindow Succeeded im.save("test.png")
注意:拷貝firefox瀏覽器的屏幕截圖有點麻煩,因為firefox的窗口句柄是無窗口句柄,只能使用UI自動化來獲取,具體操作我暫時也不會。