How to use SetPixel Function in Windows.h?


SetPixel() is a function that simply sets a pixel with the user-defined color. For Windows users, pixel operation can be easily done with C/C++ programming language. Here’s simple tutorial on “Using SetPixel Function in Windows.h”. Here, I’ve briefly introduced the need of pixels with program source code to setup SetPixel Function in Windows.h and the drawbacks of SetPixel() function.

While learning computer graphics, many times you might’ve come across creating graphical structure using pixels. To implement this in your program, a programming platform that supports pixel features is required. That is to say that the programming language, should provide the facility of printing a single pixel on the screen.

Now, let’s come to C/C++. Both support pixel operations, but you cannot print pixels in the console window. Some graphical structure mechanism is required for pixel operation in C/C++, and for Windows users, that mechanism is provided by windows.h library.

You can learn more about SetPixel function here.

SetPixel Function in Windows.h - drawing line with setpixel
Drawing Line with SetPixel

SetPixel() function, provided by windows.h can be used to print a pixel at any specified location of window. The general form of the function is:
SetPixel(HDC hdc, int x, int y, COLORREF& color);

Here, hdc is a handle to a device context, x and y are coordinates of pixel and color is the color of the pixel to be displayed. To use SetPixel() function, besides writing the command for the function and including windows.h, extra linking operation need to done.

Source Code to Implement SetPixel Function in Windows.h:

The program code presented below draws a horizontal line to a window. Note that you need to add a link library: libgdi32.a in linker setting before running the code with Code::Blocks IDE. This link library can be found usually inside MinGW\lib.

Limitations of SetPixel() Function:

SetPixel() function seems easy but for very large image data it is very slow to work. So, for such cases, instead of using SetPixel or GetPixel, bitmap functions such as BlendFunction, TransparentBlt or BitBlt can be used. The basic coding for setting some pixels with specific color on the screen using SetPixel() function is:

The problem here is that it accesses the device context for every single point individually. So, we should try to reduce accessing as well as writing in device context for every point and do more work in memory. This can done by creating a bitmap in memory. This acts as an alternative to SetPixel() function.

If you have any queries and feedback regarding the setup procedure aforementioned, bring them up from the comments section.


Please enter your comment!
Please enter your name here