Code:
#include <windows.h>
#include <stdio.h>
void cleanup( void );
LRESULT callback( HWND handle, UINT code, WPARAM wparam, LPARAM lparam );
HWND
window = 0;
HDC
foreground = 0;
HBITMAP
bitmap = 0,
saved = 0;
int main( int argc, char** argv )
{
if( argc != 2 )
{
fprintf( stderr, "- Bitmap Test -\n" );
fprintf( stderr, "Usage: %s <FILE_NAME>\n", argv[ 0 ] );
cleanup( );
return 1;
}
bitmap = HBITMAP( LoadImage( 0, argv[ 1 ], IMAGE_BITMAP, 0, 0, LR_LOADTRANSPARENT | LR_LOADFROMFILE ) );
if( bitmap == 0 )
{
fprintf( stderr, "Error: could not load file '%s'\n", argv[ 1 ] );
cleanup( );
return 2;
}
WNDCLASS
settings;
memset( &settings, 0, sizeof( settings ) );
settings.lpfnWndProc = WNDPROC( callback );
settings.hInstance = GetModuleHandle( 0 );
settings.hIcon = LoadIcon( 0, IDI_APPLICATION );
settings.hCursor = LoadCursor( 0, IDC_ARROW );
settings.lpszClassName = __FILE__;
if( !RegisterClass( &settings ) )
{
fprintf( stderr, "Error: could not register window class '%s'\n", settings.lpszClassName );
cleanup( );
return 3;
}
RECT
size;
SystemParametersInfo( SPI_GETWORKAREA, 0, &size, 0 );
window = CreateWindow
(
settings.lpszClassName,
"Bitmap Test",
WS_OVERLAPPEDWINDOW,
0,
0,
size.right - size.left,
size.bottom - size.top,
0,
0,
settings.hInstance,
0
);
if( window == 0 )
{
fprintf( stderr, "Error: could not create window" );
cleanup( );
return 4;
}
HDC
canvas = GetDC( window );
foreground = CreateCompatibleDC( canvas );
ReleaseDC( window, canvas );
saved = HBITMAP( SelectObject( foreground, bitmap ) );
ShowWindow( window, SW_SHOW );
UpdateWindow( window );
MSG
message;
while( GetMessage( &message, 0, 0, 0 ) > 0 )
{
TranslateMessage( &message );
DispatchMessage( &message );
}
cleanup( );
return message.wParam;
}
LRESULT callback( HWND handle, UINT code, WPARAM wparam, LPARAM lparam )
{
if( code == WM_CLOSE )
{
PostQuitMessage( 0 );
return 0;
}
else if( code == WM_ERASEBKGND )
{
/*
We'll redraw the background in the WM_PAINT code, instead
*/
return 1;
}
else if( code == WM_SIZE || code == WM_MOVE )
{
InvalidateRect( window, 0, 0 );
}
else if( code == WM_PAINT )
{
PAINTSTRUCT
info;
HDC
canvas = BeginPaint( window, &info );
/*
We could actually use PAINTSTRUCT::rcPaint to calculate the
dimensions, but I opted to go this route, for the sake of clarity.
*/
RECT
bounds;
GetClientRect( window, &bounds );
int
width = bounds.right - bounds.left,
height = bounds.bottom - bounds.top;
HBRUSH
saved = HBRUSH( SelectObject( canvas, GetStockObject( LTGRAY_BRUSH ) ) );
PatBlt( canvas, 0, 0, width, height, PATCOPY );
BitBlt( canvas, 0, 0, width, height, foreground, 0, 0, SRCCOPY );
SelectObject( canvas, saved );
EndPaint( window, &info );
}
return DefWindowProc( handle, code, wparam, lparam );
}
void cleanup( void )
{
SelectObject( foreground, saved );
DeleteObject( bitmap );
DeleteDC( foreground );
DestroyWindow( window );
}