在 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);
}

这是函数所在的标头

这是主要的。

#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 的文档

它说返回值是HBITMAP,而不是BITMAP

更改为:

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

删除CreateBitmapIndirect

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

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

相关内容

  • 没有找到相关文章

最新更新