/* The original version of this program can be found at http://damb.dk */
#include <windows.h>
#include <windowsx.h>
#include <commctrl.h>
#include <string.h>
#include <stdio.h>

HINSTANCE hInst;
HWND hwndMain;
HBITMAP Bitmap;
UINT ImageWidth, ImageHeight;

LRESULT CALLBACK MainWndProc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam);

HBITMAP LoadBMP(const char *FileName, UINT *Width, UINT *Height)
{
  HBITMAP BitMap = (HBITMAP )LoadImage(0, FileName, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
  if(!BitMap)
    MessageBox(0, "Failed to load image", "BitMap", MB_OK);
  else
  {
    BITMAP BitmapInfo;
    GetObject(BitMap, sizeof(BITMAP), &BitmapInfo);
    *Width = BitmapInfo.bmWidth;
    *Height = BitmapInfo.bmHeight;
  }
  return BitMap;
}

static BOOL InitApplication(void)
{
  WNDCLASS wc;

  memset(&wc,0,sizeof(WNDCLASS));
  wc.style = CS_HREDRAW|CS_VREDRAW |CS_DBLCLKS ;
  wc.lpfnWndProc = (WNDPROC)MainWndProc;
  wc.hInstance = hInst;
  wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
  wc.lpszClassName = "BitmapWndClass";
  wc.hCursor = LoadCursor(NULL,IDC_ARROW);
  wc.hIcon = LoadIcon(NULL,IDI_APPLICATION);
  if (!RegisterClass(&wc))
    return 0;

  Bitmap = LoadBMP("sample.bmp", &ImageWidth, &ImageHeight);

  return 1;
}

HWND CreateBitmapWndClassWnd(void)
{
  return CreateWindow("BitmapWndClass","Bitmap",
                      WS_MINIMIZEBOX|WS_VISIBLE|WS_CLIPSIBLINGS|WS_CLIPCHILDREN|WS_MAXIMIZEBOX|
                      WS_CAPTION|WS_BORDER|WS_SYSMENU|WS_THICKFRAME,
                      CW_USEDEFAULT,0,CW_USEDEFAULT,0,
                      NULL,
                      NULL,
                      hInst,
                      NULL);
}

void OnPaint(HWND hwnd)
{
  PAINTSTRUCT PaintStruct;
  HDC dc = BeginPaint(hwnd, &PaintStruct);
  HDC MemDC = CreateCompatibleDC(dc);
  HBITMAP OldBitmap = (HBITMAP )SelectObject(MemDC, Bitmap);
  BitBlt(dc, 0, 0, ImageWidth, ImageHeight, MemDC, 0, 0, SRCCOPY);
  SelectObject(MemDC, OldBitmap);
  DeleteObject(MemDC);
  EndPaint(hwnd, &PaintStruct);
}

LRESULT CALLBACK MainWndProc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam)
{
  switch (msg)
  {
    case WM_DESTROY:
      PostQuitMessage(0);
      break;
    case WM_PAINT:
      OnPaint(hwnd);
      return TRUE;
    default:
      return DefWindowProc(hwnd,msg,wParam,lParam);
  }

  return 0;
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, INT nCmdShow)
{
  MSG msg;

  hInst = hInstance;
  if (!InitApplication())
    return 0;

  if ((hwndMain = CreateBitmapWndClassWnd()) == (HWND)0)
    return 0;
  ShowWindow(hwndMain,SW_SHOW);

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