這是初步,主要展示取得一個 window handle 後,將其 window 存成 bmp 圖檔。至於要存哪個 window,

可再用 FindWindow 與 FindWindowEx 繼續找下去

 

#include <windows.h>
#include <stdio.h>

void CaptureScreen( HWND hwnd, char *filename)
{
    HDC hdcWindow;
    HDC hdcMemory;
    HBITMAP hBitmap;
    BYTE *lpvBits;
    BITMAPINFO bi;
    BITMAPINFOHEADER bih;
    BITMAPFILEHEADER bifh;
    HANDLE hFile;
    DWORD dwBytesWritten = 0;
    DWORD dwSize;
    int xSize, ySize;
    RECT rect;
    hdcWindow = GetDC(NULL);

    GetWindowRect(hwnd, &rect);

    xSize = rect.right - rect.left;
    ySize = rect.bottom - rect.top;
    hBitmap = CreateCompatibleBitmap(hdcWindow, xSize, ySize);
    hdcMemory = CreateCompatibleDC(hdcWindow);
    SelectObject(hdcMemory, hBitmap);
    BitBlt(hdcMemory, 0, 0, xSize, ySize, 
       hdcWindow, rect.left, rect.top, SRCCOPY);

    bih.biSize = sizeof(BITMAPINFOHEADER);
    bih.biWidth = xSize;
    bih.biHeight = ySize; 
    bih.biPlanes = 1;
    bih.biBitCount = 32;
    bih.biCompression = BI_RGB;
    bih.biSizeImage = 0;
    bih.biXPelsPerMeter = 0;
    bih.biYPelsPerMeter = 0;
    bih.biClrUsed = 0;
    bih.biClrImportant = 0;

    dwSize = (((xSize * 32 + 31)/32) * 4 * ySize);
    lpvBits = (BYTE*)malloc(dwSize);

    bifh.bfType = 0x4D42;
    bifh.bfSize = sizeof(BITMAPFILEHEADER) + 
       sizeof(BITMAPINFOHEADER) + dwSize;
    bifh.bfOffBits = (DWORD)sizeof(BITMAPFILEHEADER) + 
       (DWORD)sizeof(BITMAPINFOHEADER);
    bifh.bfReserved1 = 0;
    bifh.bfReserved2 = 0;

    bi.bmiHeader = bih;

    GetDIBits(hdcMemory, hBitmap, 0, (UINT)ySize, 
       lpvBits, &bi, DIB_RGB_COLORS);
    hFile = CreateFile(filename, GENERIC_WRITE, 0, 
       NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

    WriteFile(hFile, (LPSTR)&bifh, 
       sizeof(BITMAPFILEHEADER), &dwBytesWritten, NULL);
    WriteFile(hFile, (LPSTR)&bih, 
       sizeof(BITMAPINFOHEADER), &dwBytesWritten, NULL);
    WriteFile(hFile, (LPSTR)lpvBits, 
       dwSize, &dwBytesWritten, NULL);

    DeleteDC(hdcMemory);
    DeleteObject(hBitmap);
    CloseHandle(hFile);
    free(lpvBits);
    ReleaseDC(hwnd, hdcWindow);
}

int main()
{
    HWND hwnd = GetConsoleWindow();
    HWND hdesktop = GetDesktopWindow();
    printf("Hello, World!!");
    CaptureScreen(hwnd, "D:\\a.bmp"); /* 截取此 console 視窗圖片 */

    /* 將此 console 隱藏,避免截取桌面時截到 console window */
    // ShowWindow(hwnd, 0); 
    CaptureScreen(hdesktop, "D:\\desktop.bmp"); /* 截取目前桌面圖片 */
    return 0;
}

edisonx 發表在 痞客邦 PIXNET 留言(0) 人氣()