I am currently using the paint event on a form to draw an image onto the screen. (Think a background image) and some rectangles on top of this image.
private void MainWindow_Paint(object sender, PaintEventArgs e)
{
e.Graphics.Clear(Color.CornflowerBlue);
e.Graphics.DrawImage(Image.FromFile(m_Directory + @"\Images\" + BackgroundText), m_Screen);
e.Graphics.FillRectangle(BGBrush, new Rectangle(X, Y, Width, Height));
e.Graphics.DrawString(Text, Settings.TextFont, Other.Settings.TextBrush, new Rectangle(X, Y + 2, Width, Height));
}
The page is being repainted very often (almost on every mouse move event) and is causing huge amounts of memory to be used. Getting to 1,500,000k before it stops drawing to the form and displays the white background with red cross on the picture for a failed paint.
I am at a slight loss as to how it is running off so badly. I am new to drawing with the paint event so any help will be much appreciated!
ImageisIDisposable, so you should execute the DrawImage call within a “using” block, to ensure the Image is disposed.But most importantly, I would reconsider doing heavy IO operations in a Paint event. Possibly have the images loaded ahead of time, to have the Paint event only worry about drawing. You are currently loading the same image hundreds of times.