Home | API | MFC | C++ | C | Up

Programming Windows API

Repainting Screen with Bitmaps example

//repaint using bitmap demo
#include <windows.h>
#include <cstdlib>
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
int maxX;
int maxY;
HDC memdc;
HBITMAP hbit;
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
PWSTR lpCmdLine, int nCmdShow)
{
MSG msg ;
WNDCLASS wc = {0};
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpszClassName = TEXT("screen save");
wc.hInstance = hInstance;
wc.hbrBackground = GetSysColorBrush(COLOR_BTNFACE);
wc.lpfnWndProc = WndProc;
wc.hCursor = LoadCursor(0, IDC_ARROW);

RegisterClass(&wc);
CreateWindow(wc.lpszClassName,TEXT("Save bitmap"),WS_OVERLAPPEDWINDOW | WS_VISIBLE,100, 100, 390, 350, NULL, NULL, hInstance, NULL);

while( GetMessage(&msg, NULL, 0, 0)) {
DispatchMessage(&msg);
}

return (int) 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);
}

Home | API | MFC | C++ | C | Up
Creating a Simple Window | Common Elements | Data Types and Character Sets | The Device Context | Graphics Device Interface | Displaying Text | Displaying Graphics | Mapping Modes | Keyboard Input | Working with the Mouse | Menus | Child Windows | ScrollBar Control | The Dialog Box | Windows Message Box | Common Dialog Box | Bitmaps | Common Controls | Creating a Toolbar | Multiple Document Interface | Timers | DLL’s | Creating Custom Controls | Owner Drawn Controls | API Hooking and DLL Injection | File Management Functions | String Manipulation | System Information Functions

Last Updated: 19 September 2022