首页 > 其他 > 详细

Screen to bmp file

时间:2020-03-26 18:17:52      阅读:71      评论:0      收藏:0      [点我收藏+]
void WINAPI CaptureScreenIntoFile()
{
    BITMAPFILEHEADER bfHeader;
    BITMAPINFOHEADER biHeader;
    HGDIOBJ hTempBitmap;
    HBITMAP hBitmap;
    BITMAP bAllDesktops;
    HDC hDC, hMemDC;
    LONG lWidth, lHeight;

    ZeroMemory(&bfHeader, sizeof(BITMAPFILEHEADER));
    ZeroMemory(&biHeader, sizeof(BITMAPFILEHEADER));
    ZeroMemory(&bAllDesktops, sizeof(BITMAP));

    hDC = GetDC(NULL);
    hTempBitmap = GetCurrentObject(hDC, OBJ_BITMAP);
    GetObjectW(hTempBitmap, sizeof(BITMAP), &bAllDesktops);

    lWidth = bAllDesktops.bmWidth;
    lHeight = bAllDesktops.bmHeight;

    DeleteObject(hTempBitmap);

    bfHeader.bfType = (WORD)(B | (M << 8));
    bfHeader.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);

    biHeader.biSize = sizeof(BITMAPINFOHEADER);
    biHeader.biBitCount = 24;
    biHeader.biCompression = BI_RGB;
    biHeader.biPlanes = 1;
    biHeader.biWidth = lWidth;
    biHeader.biHeight = lHeight;
    biHeader.biSizeImage = 0;

    DWORD screen_bytes_size = (((24 * lWidth + 31) & ~31) / 8) * lHeight;

    hMemDC = CreateCompatibleDC(hDC);
    HBITMAP hbmScreen = CreateCompatibleBitmap(hDC, lWidth, lHeight);
    SelectObject(hMemDC, hbmScreen);

    int x = GetSystemMetrics(SM_XVIRTUALSCREEN);
    int y = GetSystemMetrics(SM_YVIRTUALSCREEN);
    BitBlt(hMemDC, 0, 0, lWidth, lHeight, hDC, x, y, SRCCOPY);

    HANDLE hDIB = GlobalAlloc(GHND, screen_bytes_size);
    char *lpbitmap = (char *)GlobalLock(hDIB);
    GetDIBits(hDC, hbmScreen, 0,
        (UINT)lHeight,
        lpbitmap,
        (BITMAPINFO *)&biHeader, DIB_RGB_COLORS);

    HANDLE hFile = CreateFile("12.bmp",
        GENERIC_WRITE,
        0,
        NULL,
        CREATE_ALWAYS,
        FILE_ATTRIBUTE_NORMAL, NULL);

    // Add the size of the headers to the size of the bitmap to get the total file size
    DWORD dwSizeofDIB = screen_bytes_size + sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
    bfHeader.bfSize = dwSizeofDIB;

    DWORD dwBytesWritten = 0;
    WriteFile(hFile, (LPSTR)&bfHeader, sizeof(BITMAPFILEHEADER), &dwBytesWritten, NULL);
    WriteFile(hFile, (LPSTR)&biHeader, sizeof(BITMAPINFOHEADER), &dwBytesWritten, NULL);
    WriteFile(hFile, (LPSTR)lpbitmap, screen_bytes_size, &dwBytesWritten, NULL);

    DeleteDC(hMemDC);
    ReleaseDC(NULL, hDC);
    DeleteObject(hbmScreen);
}

 

Screen to bmp file

原文:https://www.cnblogs.com/strive-sun/p/12575884.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!