Back

Win32 let me draw

Assuming you are using win32 to create a window and would like to call give_me_a_buffer_to_draw_to(), here's some code that does that.

I've compiled it with clang++ main.cpp -luser32 -lgdi32, you can use your favorite compiler.

The code is fairly straightforward, but I'd like to highlight some points:

  • It repaints the bitmap every frame. The snippets I've seen from the Microsoft docs had a copy of the bitmap blitting code duplicated inside the WM_PAINT event. I didn't find any info as to why this is needed so I've decided to not do that.
  • I wasn't sure how to handle minimizing a window so it just loops until it's not minimized.
  • The resizeBitmap() function is quite overloaded and not properly named. It currently handles creating, deleting, and resizing (by deleting and recreating) the bitmap. It could be split into different functions.
  • I've seen some code handling deleting the bitmap memory by getting the old handle from the return value of SelectObject(). It didn't work for me, so I store the bitmap's handle.
  • One point of confusion was that I allocated the buffer memory myself leading to memory leaks and errors. CreateDIBSection handles allocating the memory by itself.
  • I use biBitCount = 32 even if I don't necessarily need the alpha byte. I just think the advantage of not having to align the width to the nearest DWORD is a nicer API. If you were concerned about memory and wanted to use 24 bits there is a simple formula for the alignment and some additional info on the documentation .

Since this post is quite short, I'm going to pad it out with the AI overlord (ChatGPT 3.5) thoughts on the code:

The code looks straightforward and relatively simple. It creates a window using the Win32 API, registers a window class, and sets up a message loop to handle messages sent to the window. The code also defines a WinBuffer struct to hold information about the buffer used for drawing, and a function resizeBitmap to handle resizing of the window and the buffer. The function WindowProc handles messages sent to the window, including the WM_SIZE message that triggers a resize of the window and the buffer. The message loop in the wWinMain function uses PeekMessage to check for messages in the message queue, and if there are none, it updates the buffer with a simple gradient and draws it to the screen using BitBlt. Overall, the code looks like a good starting point for creating a window and drawing to a buffer in Win32.

AI approved, I'm safe!