Programming Tip: Draw a pixel on Windows Forms

winforms graphics pixel

There was a function called PSet in Visual Basic 6 that allowed an easy way of drawing a pixel on a form. But this feature is missing in the VB.NET.


The Windows Forms Graphics object does not provide a simple way of drawing a pixel on the screen, form or a window.


To resolve that issue and draw a pixel, we can use the following code.

Brush aBrush = (Brush)Brushes.Black;
Graphics g = this.CreateGraphics();

g.FillRectangle(aBrush, x, y, 1, 1);

Here aBrush is the Brush object used to specify the color of the pixel.

I can also create a simple function that can be easily reused.

void DrawPixel(Graphics g, Brush aBrush, int x, int y)
    g.FillRectangle(aBrush, x, y, 1, 1);

And then to call that function, simply call this.

DrawPixel(this.CreateGraphics(), (Brush)Brushes.Black, 100, 100);


So, this example shows that it is very easy to overcome this shortcoming of the Graphics object. I look forward to feedback and will continue to share similar tips.