在 C 中创建 BITMAP 时初始值设定项无效

Invalid initializer when creating a BITMAP in C

我正在尝试制作一个截屏并保存的程序,直到现在它只将它保存到一个变量 (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);
}

这是函数所在的header

这里是 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);
}

请参阅 CreateCompatibleBitmap

的文档

它说 return 值是 HBITMAP,而不是 BITMAP

更改为:

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

删除CreateBitmapIndirect

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

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