WinAPI : SetPixel Function
We got a feel of what a Device Context is in a earlier post WinAPI : Starting with Device Context. Let’s explore ahead.
We already learnt how to get the handle to the Device Context of a window using GetDC function.
All VB objects that have a Device Context associated with them allow you to get the handle to the device context by accessing the hDC property of the object say of the form.
Let’s take a few functions related to drawing on Device Contexts.
The smallest/basic geometrical shape is a point.
A point is drawn on a Device Context using SetPixel function.
Private Declare Function SetPixel Lib "gdi32" (ByVal hdc As Long, _
ByVal x As Long, ByVal y As Long, ByVal crColor As Long) As Long
The function takes handle to the device context as the first parameter. The next two parameters are the X and Y co-ordinates where point is to be drawn. The last parameter is the color of the pixel which can be passed using RGB function.
Let’s get to draw a pixel on a given position on form within MouseMove event of the form.
Private Sub Form_MouseMove(Button As Integer, _
Shift As Integer, X As Single, Y As Single)
SetPixel Form1.hdc, X / Screen.TwipsPerPixelX, _
Y / Screen.TwipsPerPixelX, RGB(0, 0, 0)
End Sub
![]()
Copy the codes above to the code section of form and execute. Whenever the MouseMove event is fired a pixel is drawn on the position below cursor.



[...] present at a particular co-ordinate on a device context, or set the desired color. For details read WinAPI : SetPixel Function and WinAPI : GetPixel [...]
The Blog Revisited - 5 « Jalaj P. Jha
December 11, 2008 at 12:43 am
[...] Filed under: WinAPI, Visual Basic, Application — Jalaj @ 7:24 am In previous post WinAPI : SetPixel Function we used SetPixel function to draw over a particular point with a particular [...]
WinAPI : GetPixel Function « Jalaj
February 22, 2007 at 8:04 am