Repainting the Screen Using Device Dependent Bitmaps


//repaint using bitmap demo
#include <windows.h>
#include <cstdlib>
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
int maxX;
int maxY;
HDC memdc;
HBITMAP hbit;
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
WNDCLASSEX wc;
MSG msg;
wc.cbSize = sizeof(WNDCLASSEX);
wc.style = 0;
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("myWindowClass");
wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
RegisterClassEx(&wc);
CreateWindowEx(WS_EX_CLIENTEDGE, TEXT("myWindowClass"), TEXT("Repaint the Screen"), WS_VISIBLE | WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 700, 200, NULL, NULL, hInstance, NULL);
while (GetMessage(&msg, NULL, 0, 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 lpRect;
GetClientRect(hwnd,&lpRect);
maxX=lpRect.right-lpRect.left;
maxY=lpRect.bottom-lpRect.top;
int randx;
int randy;
int p;
hdc = GetDC(hwnd);//create a device context
memdc=CreateCompatibleDC(hdc);//creates a compatible device context copy
hbit=CreateCompatibleBitmap(hdc,maxX,maxY);//creates bitmap of current device context
SelectObject(memdc,hbit);//copies device content bit map into device context copy
PatBlt(memdc,0,0,maxX,maxY,PATCOPY);//copy current brush into device context copy
//creates 200 random lines in device context copy
for (p=0;p<200;p++)
{
randx= (rand() % maxX) + 1;
randy= (rand() % maxY) + 1;
LineTo(memdc, randx, randy);
}

ReleaseDC(hwnd,hdc);
break;

case WM_PAINT:
//copies compatible device image into device context before repainting window
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);
break;

case WM_DESTROY:
ReleaseDC(hwnd,memdc);
PostQuitMessage(0);
return 0;
}

return DefWindowProc(hwnd, msg, wParam, lParam);
}