-1

我正在尝试制作一个拍摄屏幕截图并保存它的程序,直到现在它只将它保存到一个变量(hbCapture)中。尽管代码似乎是编写的并且我已经阅读了多次文档,但它在创建 BITMAP 时给了我一个无效的初始化程序错误。

#include <stdlib.h>
#include <windows.h>
#include <stdbool.h>
#include <wingdi.h>
#include <winuser.h>

typedef unsigned char u8;
typedef unsigned short u16;
typedef unsigned long u32;
typedef unsigned long long u64;

void getScreen()
{
    u16 screenHeight = GetSystemMetrics(SM_CYVIRTUALSCREEN);
    u16 screenWidth = GetSystemMetrics(SM_CXVIRTUALSCREEN);

    HDC hdc = GetDC(NULL); //get a desktop dc (NULL for entire screen)
    HDC hDest = CreateCompatibleDC(hdc); //create a dc for capture

    BITMAP hbCapture = CreateCompatibleBitmap(hdc, screenWidth, screenHeight);
    SelectObject(hDest, hbCapture);

    //Copy screen to bitmap
    BitBlt(hDest, 0, 0, screenWidth, screenHeight, hdc, 0, 0, SRCCOPY);

    //Clean up
    ReleaseDC(NULL, hdc);
    DeleteDC(hDest);
}

这是函数所在的标题

这是main.c

#include "main.h"

int main()
{
    getScreen();

    return 0;
}

--------------------------这个我也试过了,还是不行-------------- ------------------------------------------

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <stdbool.h>
#include <wingdi.h>
#include <winuser.h>

typedef unsigned char u8;
typedef unsigned short u16;
typedef unsigned long u32;
typedef unsigned long long u64;

void getScreen()
{
    u16 screenHeight = GetSystemMetrics(SM_CYVIRTUALSCREEN);
    u16 screenWidth = GetSystemMetrics(SM_CXVIRTUALSCREEN);

    HDC hdc = GetDC(NULL); //get a desktop dc (NULL for entire screen)
    HDC hDest = CreateCompatibleDC(hdc); //create a dc for capture

    //test
    ReleaseDC(NULL, hdc);
    //DeleteDC(hdc);
    //test

    BITMAP bCapture = CreateCompatibleBitmap(hdc, screenWidth, screenHeight);
    HBITMAP hbCapture = CreateBitmapIndirect(&bCapture);
    SelectObject(hDest, hbCapture);

    //Copy screen to bitmap
    BitBlt(hDest, 0, 0, screenWidth, screenHeight, hdc, 0, 0, SRCCOPY);

    //Clean up
    ReleaseDC(NULL, hdc);
    DeleteDC(hDest);
}

4

1 回答 1

0

请参阅CreateCompatibleBitmap的文档

它说返回值是HBITMAP,不是BITMAP

改成:

HBITMAP hbCapture = CreateCompatibleBitmap(hdc, screenWidth, screenHeight);

消除CreateBitmapIndirect

然后,您需要GetDIBits将位图标题和像素保存到文件中。

还包括DeleteObject(hbCapture)在代码的末尾进行清理。

于 2019-09-14T19:07:26.260 回答