窗口编程API - LoadImage

我正在学习窗口API编程 . 但是我陷入了加载图像并在窗口上显示的问题 .

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

#define wname "mywin"

LRESULT CALLBACK WndProc(HWND h,UINT im,WPARAM wp,LPARAM lp);

int APIENTRY  WinMain(HINSTANCE his, HINSTANCE prev,LPSTR cmd, int cshow)
{        

    WNDCLASS wc;

    wc.cbClsExtra=0;
    wc.cbWndExtra=0;
    wc.hbrBackground=(HBRUSH)GetStockObject(WHITE_BRUSH);
    wc.hCursor=LoadCursor(NULL,IDC_ARROW);
    wc.hIcon=LoadIcon(NULL,IDI_APPLICATION);
    wc.lpszMenuName=NULL;
    wc.style=CS_HREDRAW | CS_VREDRAW;

    wc.hInstance = his;                  
    wc.lpszClassName = wname;           
    wc.lpfnWndProc = (WNDPROC)WndProc;    

    RegisterClass(&wc);

    HWND h = CreateWindow(wname, wname, WS_OVERLAPPEDWINDOW,
        CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
        NULL, (HMENU) NULL, his, NULL );

    ShowWindow(h, cshow);

    MSG Message;    
    while(GetMessage(&Message,0,0,0)) 
    {
        TranslateMessage(&Message);
        DispatchMessage(&Message);
    }

}

LRESULT CALLBACK WndProc(HWND h, UINT im, WPARAM wp, LPARAM lp)
{
    HBITMAP static hbm;
    HDC static mdc;
    BITMAP static bm;

    switch(im)
    {
        case WM_CREATE: 
        {        
            hbm = (HBITMAP) LoadImage(NULL, "../img/1.bmp", IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);   
            GetObject(hbm, sizeof(bm), &bm);

            if(!hbm)
            {
                MessageBox(h, "Error loading bitmap", "msg", MB_OK);  
            }

            break;    
        }

        case WM_PAINT:
        {
            HDC hdc = GetDC(h);
            mdc = CreateCompatibleDC(hdc);    
            SelectObject(mdc, hbm);  

            BitBlt(hdc, 0, 0, bm.bmWidth, bm.bmHeight, mdc, 0, 0, SRCCOPY);

            break;        
         }
}

我试过这段代码 . 没有语法错误,但输出很奇怪 . 出现图片,但没有窗口,程序停止 . 我认为问题出现在'LRESULT CALLBACK WndProc'中的WM_CREATE部分,但无法弄清楚到底出了什么问题 . 救命!!! (WinMain没问题,这里没问题)

回答(1)

2 years ago

您似乎没有 WndProc 的返回值,并且默认情况下可能不会处理Win32消息 .

(在 case WM_PAINT 之后):

case WM_DESTROY:
      PostQuitMessage(0);
      break;

    default:
      return DefWindowProc(hWnd, message, wParam, lParam);
  }
  return 0;
}