Repainting the Screen Using Device Dependent Bitmaps
#include <windows.h>
#include <stdlib.h>
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
int maxX, maxY;
HDC memDC = NULL;
HBITMAP hBitmap = NULL;
HBITMAP hOldBitmap = NULL;
int WINAPI WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
WNDCLASSEX wc;
MSG msg;
wc.cbSize = sizeof(WNDCLASSEX);
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wc.lpszMenuName = NULL;
wc.lpszClassName = TEXT("BitmapDemo");
wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
RegisterClassEx(&wc);
CreateWindowEx(
WS_EX_CLIENTEDGE,
TEXT("BitmapDemo"),
TEXT("Repaint Using Bitmap"),
WS_OVERLAPPEDWINDOW | WS_VISIBLE,
CW_USEDEFAULT,
CW_USEDEFAULT,
700,
300,
NULL,
NULL,
hInstance,
NULL);
while(GetMessage(&msg,NULL,0,0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
LRESULT CALLBACK WndProc(HWND hwnd,
UINT msg,
WPARAM wParam,
LPARAM lParam)
{
HDC hdc;
PAINTSTRUCT ps;
switch(msg)
{
case WM_CREATE:
{
RECT rc;
int i;
int x1,y1,x2,y2;
GetClientRect(hwnd,&rc);
maxX = rc.right;
maxY = rc.bottom;
hdc = GetDC(hwnd);
memDC = CreateCompatibleDC(hdc);
hBitmap = CreateCompatibleBitmap(
hdc,
maxX,
maxY);
hOldBitmap = (HBITMAP)SelectObject(
memDC,
hBitmap);
PatBlt(
memDC,
0,
0,
maxX,
maxY,
WHITENESS);
srand(GetTickCount());
for(i=0;i<200;i++)
{
x1 = rand() % maxX;
y1 = rand() % maxY;
x2 = rand() % maxX;
y2 = rand() % maxY;
MoveToEx(memDC,x1,y1,NULL);
LineTo(memDC,x2,y2);
}
ReleaseDC(hwnd,hdc);
return 0;
}
case WM_PAINT:
hdc = BeginPaint(hwnd,&ps);
BitBlt(
hdc,
ps.rcPaint.left,
ps.rcPaint.top,
ps.rcPaint.right - ps.rcPaint.left,
ps.rcPaint.bottom - ps.rcPaint.top,
memDC,
ps.rcPaint.left,
ps.rcPaint.top,
SRCCOPY);
EndPaint(hwnd,&ps);
return 0;
case WM_DESTROY:
if(memDC)
{
SelectObject(memDC,hOldBitmap);
DeleteObject(hBitmap);
DeleteDC(memDC);
}
PostQuitMessage(0);
return 0;
}
return DefWindowProc(hwnd,msg,wParam,lParam);
}