windows 无法为WinApi中的窗口设置背景图像

o2rvlv0m  于 2022-11-18  发布在  Windows
关注(0)|答案(1)|浏览(193)

我正在学习如何在C中设置窗口的背景图像。下面是我的代码:

#include <stdio.h>
#include <windows.h>

char* window_name = "Window";
char* window_title = "Window Title";
char* background_name = "test.bmp";
int window_width = 600;
int window_height = 400;

HBITMAP hbackground_image;
WNDCLASSEX wc;
HWND hwnd, hbackground;
MSG msg;

LRESULT CALLBACK WindowProcedure(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
{
    switch (msg)
    {
    case WM_CREATE:
        hbackground = CreateWindow("STATIC", "background", SS_BITMAP | WS_CHILD | WS_VISIBLE, 0, 0, 300, 300, hwnd,
                                   NULL, NULL, NULL);
        hbackground_image = (HBITMAP)LoadImage(NULL, background_name, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
        SendMessage(hbackground, STM_SETIMAGE, (WPARAM)IMAGE_BITMAP, (LPARAM)hbackground_image);
        break;
    default:
        return DefWindowProc(hwnd, msg, wp, lp);
    }
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    wc.cbSize = sizeof(WNDCLASSEX);
    wc.style = CS_HREDRAW | CS_VREDRAW;
    wc.lpfnWndProc = DefWindowProc;
    wc.cbClsExtra = 0;
    wc.cbWndExtra = 0;
    wc.hInstance = hInstance;
    wc.hIcon = LoadIcon(hInstance, IDI_APPLICATION);
    wc.hCursor = LoadCursor(NULL, IDC_ARROW);
    wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
    wc.lpszMenuName = NULL;
    wc.hIconSm = LoadIcon(hInstance, IDI_APPLICATION);
    wc.lpszClassName = window_name;

    if (!RegisterClassEx(&wc))
    {
        MessageBox(NULL, "Windows registration failure", NULL, MB_RETRYCANCEL);
        return 1;
    }
    hwnd = CreateWindowEx(WS_EX_OVERLAPPEDWINDOW, window_name, window_title, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT,
                          CW_USEDEFAULT, window_width, window_height, NULL, NULL, hInstance, NULL);
    // hwnd = CreateWindow("test", "test title", WS_OVERLAPPED | WS_VISIBLE, 100, 100, 500, 500, NULL, NULL, NULL, NULL); // This fails
    if (!hwnd) // If fails
    {
        MessageBox(NULL, "Window creation failed :(", NULL, MB_RETRYCANCEL);
        return 2;
    }
    ShowWindow(hwnd, nCmdShow);
    UpdateWindow(hwnd);

    while (GetMessage(&msg, NULL, 0, 0) > 0)
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    return msg.wParam;
}

然而,即使在. exe文件夹中有位图,背景图像也无法设置。我也尝试了从互联网上下载不同的位图,还有一个是我用paint制作的。如果有任何帮助,我将不胜感激。

nkoocmlb

nkoocmlb1#

这一行是错的:

wc.lpfnWndProc = DefWindowProc;

您看不到背景图像,因为您没有将WindowProcedure()与window类一起使用,因此从未调用它来加载/显示位图。
该行需要改为:

wc.lpfnWndProc = WindowProcedure;

此外,在处理WM_CREATE时,您没有return处理任何值,因此结果是 * 不确定 *,这是 * 未定义的行为 *。您需要为该消息执行return 0;

LRESULT CALLBACK WindowProcedure(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
{
    switch (msg)
    {
    case WM_CREATE:
        ...
        return 0;
    ...
    }
    return DefWindowProc(hwnd, msg, wp, lp);
}

相关问题