Rachel.S
Rachel.S

Reputation: 7

window programming API - LoadImage

I am learning window API programming. However I am getting stuck in loading image and showing on the window.

#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;        
         }
}

I tried this code. There is no grammer error, but the output is wierd. Picture appears, but without window, and the program stopped. I think the probelm is on WM_CREATE part in 'LRESULT CALLBACK WndProc' , but cannot figure out exactly what is wrong. HELP!!! (WinMain is ok, here is no problem)

Upvotes: 0

Views: 399

Answers (1)

i486
i486

Reputation: 6563

It seems you have no return value for WndProc and probably Win32 messages are not processed by default.

(after case WM_PAINT):

    case WM_DESTROY:
      PostQuitMessage(0);
      break;

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

Upvotes: 1

Related Questions