I have the code below that is supposed to draw lines from the top to the bottom of a fullscreen form.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
Graphics g;
public Form1()
{
InitializeComponent();
g = CreateGraphics();
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
Pen pen = new Pen(Color.Black);
for (int i = 0; i < this.ClientSize.Height; i++)
{
g.DrawLine(pen, 100, i, 50, i);
}
}
}
}
The form in question (Form1) is maximized, borderless and topmost. Result of the code is, form is displayed, lines are drawn one after another but when the number i of the loop reaches 1055 DrawLine starts not working and until the end of the loop from then on notghing else is drawn, therefore there is a blank space at the bottom of the form.
some extra information
My desktop resolution is 1920 x 1080
this.Size = 1920 x 1080
this.ClientSize = 1920 x 1080
Anyone is welcomed to create an empty project, set form properties (maximized, topmost, borderless) and copy-paste this code to reproduce the problem I have.
Here’s fixed code:
The graphics object is meant to be used right away and then disposed. The main reason is, there is a real windows Device Context (HDC) that is used by the graphics object. This is a limited resource, and if you tie up too many in the program windows will cut the program off. If you have too many programs using too many, you’ll actually crash windows’ UI, or at least parts of it, although each subsequent version of windows adds protections to prevent this. Disposing the HDC explicitly and immediately with .Dispose or the using construct, when you’re done drawing, is required; by the time the GC gets around to it, you could have used them all up.
The framework will create the Graphics and Dispose of it for you in the paint event. So when you’re drawing in paint (recommended), you don’t have to dispose the graphics.
Any time you use creategraphics on a form, or Graphics.FromImage or similar, you should use it and dispose of it ASAP.
Because of this design and the requirements that go with it, the HDC makes assumptions about the window at the moment it is grabbed. In the interem, the window could maximize or resize itself before drawing on it occurs again. The paint event also grabs another one from the same window handle – an unusual usage of HDC – so it is probably one of these issues which is causing the strange behaviour.