C ++截图

时间:2016-02-09 03:42:40

标签: c++ screen screenshot

我使用此代码在Windows上截取屏幕截图:

keybd_event(VK_SNAPSHOT, 0x45, KEYEVENTF_EXTENDEDKEY, 0);
keybd_event(VK_SNAPSHOT, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
HBITMAP h;

OpenClipboard(NULL);
h = (HBITMAP)GetClipboardData(CF_BITMAP);
CloseClipboard();
HDC hdc = NULL;
FILE*fp = NULL;
LPVOID pBuf = NULL;
BITMAPINFO bmpInfo;
BITMAPFILEHEADER bmpFileHeader;
do
{
    hdc = GetDC(NULL);
    ZeroMemory(&bmpInfo, sizeof(BITMAPINFO));
    bmpInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
    GetDIBits(hdc, h, 0, 0, NULL, &bmpInfo, DIB_RGB_COLORS);
    if (bmpInfo.bmiHeader.biSizeImage <= 0)
        bmpInfo.bmiHeader.biSizeImage = bmpInfo.bmiHeader.biWidth*abs(bmpInfo.bmiHeader.biHeight)*(bmpInfo.bmiHeader.biBitCount + 7) / 8;
    if ((pBuf = malloc(bmpInfo.bmiHeader.biSizeImage)) == NULL)
    {
        MessageBox(NULL, "Unable to Allocate Bitmap Memory", "Error", MB_OK | MB_ICONERROR);
        break;
    }
    bmpInfo.bmiHeader.biCompression = BI_RGB;
    GetDIBits(hdc, h, 0, bmpInfo.bmiHeader.biHeight, pBuf, &bmpInfo, DIB_RGB_COLORS);
    if ((fp = fopen(filename, "wb")) == NULL)
    {
        MessageBox(NULL, "Unable to Create Bitmap File", "Error", MB_OK | MB_ICONERROR);
        break;
    }
    bmpFileHeader.bfReserved1 = 0;
    bmpFileHeader.bfReserved2 = 0;
    bmpFileHeader.bfSize = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + bmpInfo.bmiHeader.biSizeImage;
    bmpFileHeader.bfType = 'MB';
    bmpFileHeader.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
    fwrite(&bmpFileHeader, sizeof(BITMAPFILEHEADER), 1, fp);
    fwrite(&bmpInfo.bmiHeader, sizeof(BITMAPINFOHEADER), 1, fp);
    fwrite(pBuf, bmpInfo.bmiHeader.biSizeImage, 1, fp);
}

while (false);
if (hdc)ReleaseDC(NULL, hdc);
if (pBuf) free(pBuf);
if (fp)fclose(fp);

我不知道为什么有时会起作用,有时却不行。如果没有工作给我一个54字节的黑色图像。

另外,我可以阅读以了解如何获取该屏幕截图的特定区域?

0 个答案:

没有答案