Tomas
Tomas

Reputation: 621

How to re-size the client area when double buffering?

Given I implement double buffering in GDI:

static HDC hdc;
static HDC backDC;
static HBITMAP backBuffer;
static HGDIOBJ oldBitmap;
static RECT client;

case WM_CREATE:     
     hdc=GetDC(hWnd);
    GetClientRect(hWnd, &client);
    backDC=CreateCompatibleDC(hdc);         
    backBuffer=CreateCompatibleBitmap(hdc,client.right,client.bottom);
    oldBitmap=SelectObject(backDC,backBuffer);
    ReleaseDC(hWnd,hdc);

case WM_PAINT:


Rectangle(backDC, 0, 0,client.right,client.bottom); // displays rectangle the
 size of client to draw on it
      hdc = BeginPaint(hWnd, &ps);  
      BitBlt(hdc,0,0,client.right,client.bottom,backDC,0,0,SRCCOPY);
    // TODO: Add any drawing code here...
       EndPaint(hWnd, &ps);

How do I handle the resize ? One thing I have tried to do is

case WM_SIZE:   
client.right=LOWORD(lParam);
client.bottom=HIWORD(lParam);
    SendMessage(hWnd,WM_CREATE,NULL,NULL);

What it does is, once I get resize message with new client coordinates it sends message to WM_CREATE and it actually works.... HOWEVER ! It creates massive leak, because I basically create a new bitmap every time without destroying it. Can someone tell me if there is a better way to do it ? Thx

Upvotes: 0

Views: 486

Answers (2)

Jim Mischel
Jim Mischel

Reputation: 134125

I would recommend making the back buffer a fixed size (typically, the size of the screen), and then using StretchBlt (or StretchDIBits if you're using DIBs) to render it in the proper size on the display surface.

That way, you never have to worry about reallocating the back buffer.

Upvotes: 0

Adrian McCarthy
Adrian McCarthy

Reputation: 48038

Keeping the backbuffer around is an optimization that's not always needed. You can create it in the WM_PAINT handler (to the size of GetClientRect), paint to it, blit from it to the actual window DC, and clean up. No leaks. No distribution of functionality among all the message handlers. No global variables. Nice and clean.

If you do want to keep one around, I make a class. Constructor takes the size. Destructor cleans up everything. On WM_SIZE, construct a new one as a local stack variable, swap with the old one, and let destructor for the temp stack one clean up.

Upvotes: 1

Related Questions