top of page

Drawing individual pixels with the Windows API

  • Writer: John
    John
  • 3 days ago
  • 2 min read
This post is one of a series providing implementation examples of Windows API Functions, Types, Enums and Consts using VBA. The code in this post can be used as-is, however, if you regularly (or even just occasionally) work with Windows API declarations in VBA, you may want to see the posts Automatically add Windows API declaration(s) and Using 'F1' to view Windows API web pages which explain some of the functionality that can be added to the VBE by VBE_Extras.

There are two key Windows API Functions used in this example code to draw pixels. The first is SetPixel which sets the pixel at the specified coordinates to the specified RGB colour. However, before you can set (or get) a pixel, you need the 'device context' which is passed into SetPixel as its 'hdc' parameter. To get the device content, the GetDC Windows API Function is used ... this "returns a handle to a device context for ... a specified window ... you can use the returned handle in subsequent GDI functions to draw on the device context". Sounds just like what we need.


The second key Windows API Function is GetPixel which gets the RGB colour value of the pixel at the specified coordinates. Obviously, you don't need this if all you want to do is set the colour of pixels. But in this example, I want to also demonstrate getting pixel colours in order to invert the existing colour.


There's really not much more to explain about these two Functions other than the fact that the coordinates they use are in pixels and the coordinates used by a UserForm (in this example, the pixels are being drawn on the device context of a UserForm) are in points so we need to convert between the two which, in the example code, is done using the GetPointsPerPixel Function.


One thing to note, though, is that drawing a lot of individual pixels (and, even more, getting the colour of a lot of individual pixels) is not fast. You wouldn't want to be sat waiting while millions of pixels are being drawn!


This is the result of the code having drawn the pixels with SetPixel:


A UserForm with drawn pixels

And this is the result of the code having inverted the pixels with GetPixel and SetPixel:


A UserForm with inverted pixels

The following code should be put into the code-behind of a UserForm that has a CommandButton in the lower/right corner named CommandButton1 (I changed the caption to "Click me!"). In the example, the UserForm has a width of 240 and a height of 180.



And this code can go in a standard Module which you can then run



Or you can just download this Workbook which contains all of the necessary code, then you can just click the button on the Worksheet to run the code.



To read more about the other Windows API Functions used in the code:





bottom of page