Click to choose your tutorial
Tutorial 1: SDK
Tutorial 2: Creating a Window
Tutorial 3: Vulkan Instance
Tutorial 4: Supported Extensions
Tutorial 5: Drawing Points
Tutorial 6: Drawing Lines
Tutorial 7: Drawing Triangles
Tutorial 8: Introduction to Shaders
Tutorial 9: Loading Shaders
Tutorial 10: Using Multiple Shaders
Tutorial 11: Loading 3D Model
Tutorial 12: Displaying 3D Model
Tutorial 13: Vertex Animation
Tutorial 14: Bone Animation
OpenGL Tutorials
site is v0.1a build Sep 11, 2016
Join to be notified of new tutorials
Join

Win32 API Tutorial 3 - How To Draw Pixels in A Window Using GDI in Win32 API (Graphics Device Interface)

Written by staff. Contact us to submit your article for review.
Sep 13, 2016
tags Tags first, window, win32api
Post #38

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); while(!quit) { if(PeekMessage(&msg, NULL, NULL, NULL, PM_REMOVE)) { if(msg.message == WM_QUIT) quit = true; TranslateMessage(&msg); DispatchMessage(&msg); } 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.

article tab
Follow OpenGL Tutorials
You will only receive important news about OpenGL tutorial updates.
Who is joining?
  • Programmers You want to stay in touch to receive OpenGL tutorial updates.
  • Game Devs You're a game developer, and you also want to learn more about OpenGL!
  • Supporters You have invested interest in supporting OpenGL tutorial site.
Follow OpenGL Tutorials
Follow