语境 :
- 视窗 10
- WinAPI 和 C 代码
问题 :
我有一个像素缓冲区,表示uint8_t buffer[width * height * PIXEL_SIZE]
我想定期修改内容数据并将缓冲区重绘到窗口中。
我遇到了两个与我迷路的winapi有关的问题:
- 如何在窗口上打印像素缓冲区?
- 我如何稍后在 dame 修改缓冲区的代码中重绘?
我做了很多研究,但没有代码片段成功地帮助我解决了我的问题。
这是一个不工作的代码示例,以显示我想用我拥有的代码元素归档的内容:
new_image.c
// Global variables
static HDC hdc;
static HDC context_hdc;
static HBITMAP hDib;
static HGDIOBJ obj;
static void set_bmi_object(BITMAPINFO *bmi, int width, int height) {
memset(bmi, 0, sizeof(BITMAPINFO));
bmi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bmi->bmiHeader.biWidth = width;
bmi->bmiHeader.biHeight = -height;
bmi->bmiHeader.biPlanes = 1;
bmi->bmiHeader.biBitCount = 32;
bmi->bmiHeader.biCompression = BI_RGB;
}
// Allocate a new image buffer
void *new_image(HWND hwnd, int width, int height)
{
BITMAPINFO bmi;
BYTE *bits = NULL;
void *buffer;
if (NULL == (buffer = (char*)malloc(width * height * PIXEL_SIZE)))
return (NULL);
set_bmi_object(&bmi, width, height);
hdc = GetDC(hwnd);
hDib = CreateDIBSection(hdc, &bmi, DIB_RGB_COLORS, (void**)(&bits),
NULL, 0);
if (hDib != NULL) {
context_hdc = CreateCompatibleDC(hdc);
if (context_hdc == NULL) {
DeleteObject(hDib);
} else {
obj = SelectObject(context_hdc, hDib);
CopyMemory(bits, buffer, width * height * sizeof(PIXEL_SIZE));
}
}
return (newimg);
}
// Print the buffer of pixel on the window
void put_image_to_window(HWND hwnd, void *buffer, int x, int y)
{
(void)hwnd;
// Void buffer because i should use directly HDCcontext_hdc linked to HGDIOBJ obj ?
(void)buffer;
BitBlt(hdc, // destination
x,
y,
500, // width of the region
500, // height
context_hdc, // source
0, // x
0, // y
SRCCOPY);
UpdateWindow(hwnd);
}
主程序
static const char g_szClassName[] = "myWindowClass";
static void paint(HWND hwnd) {
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
EndPaint(hwnd, &ps);
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case WM_CLOSE:
DestroyWindow(hwnd);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
case WM_PAINT:
paint(hwnd);
return DefWindowProc(hwnd, msg, wParam, lParam);
}
int main(void) {
MSG Msg;
HINSTANCE hInstance;
HWND hwnd;
STARTUPINFOA startup_info;
WNDCLASSEX wc;
HWND hwnd;
GetStartupInfoA(&startup_info);
hInstance = GetModuleHandle(NULL);
memset(&wc, 0, sizeof(wc));
// Registering the Window Class
wc.cbSize = sizeof(WNDCLASSEX);
// ... etc
wc.lpszClassName = TEXT(g_szClassName);
if (!RegisterClassEx(&wc)) {
return (-1);
}
hwnd = CreateWindowEx(
WS_EX_CLIENTEDGE,
g_szClassName,
"Title,
WS_OVERLAPPEDWINDOW | WS_VISIBLE,
CW_USEDEFAULT,
CW_USEDEFAULT,
500,
500,
NULL,
NULL,
hInstance,
NULL);
if (hwnd == NULL) {
return (-1);
}
ShowWindow(hwnd, startup_info.wShowWindow);
image = new_image(hwnd, 500, 500);
put_image_to_window(hwnd, image, 0, 0);
UpdateWindow(hwnd);
// The Message Loop
while (GetMessage(&Msg, NULL, 0, 0)) {
TranslateMessage(&Msg);
DispatchMessage(&Msg);
}
return (Msg.wParam);
}
这是在new_image.c
一个返回像素缓冲区指针的函数
new_image
,一个
put_image_to_window
在窗口上显示像素缓冲区的函数。