Be Friendly
Search This Site for Tutorials About...

How to Draw Pixels in A Window Using GDI (Graphics Device Interface)

Just for fun: How to Make French Toast

In the previous tutorial you learned how to create a window on the screen and wrote a message loop system. In this tutorial you'll learn how to draw some pixels inside the window you created. I can already tell that this is going to be a short tutorial but it gives you the basics of drawing in a window. I'll take the windows program from the previous tutorial and for this tutorial most of the code will be located inside the message loop.

To start drawing anything in a window you will need to obtain a copy of its device context. And after you're done drawing you have to release the device context. You can do that with the following two calls:

// Get DC
HDC hdc = GetDC(hwnd);

// Release DC
ReleaseDC(hwnd, hdc);

The code for drawing pixels doesn't require rocket science knowledge. To draw a pixel on the screen you have to call SetPixel and pass the location of the pixel in window coordinates, its color and the DC. I'll insert the pixel drawing code into the previous tutorial's base code inside the message loop.

// The message loop

HDC hdc = GetDC(hwnd);

	if(PeekMessage(&msg, NULL, NULL, NULL, PM_REMOVE))
		if(msg.message == WM_QUIT)
			quit = true;
	for(int i = 0; i < 1000; i++)
		int x = rand()%300;
		int y = rand()%300;
		SetPixel(hdc, x, y, RGB(rand()%255, 0, 0));

ReleaseDC(hwnd, hdc);

This code will draw 1000 randomly shaded and positioned pixels inside the window each frame. Find out how to draw lines, circles and rectangles by snooping through the msdn help files. I did. It's a good practice. Or otherwise, if anyone feels really lost, you can send me a tutorial request.

Did this article help you learn something new?

I enjoy writing for the Internet audiences because my thoughts are instantly published to the entire world. My work consists of writing educational articles about making websites to help people learn. If you enjoyed reading this article, or learned something new, then I have succeeded.

If the content on this website somehow helped you to learn something new, please let others know about it by sharing it on your website or on your Facebook page with your friends. In addition you can help by making a donation or bookmarking this site.