BoCoKeith
BoCoKeith

Reputation: 946

WinForms Draw Problem (What Obvious Thing Am I Missing)

When I run the following code, the image I have loaded in the MyPictureBox object briefly flashes, but then the form is immediately overwritten with the standard Windows background color.

I know I am missing something really obvious. (P.S. the form has no controls other than the MyPictureBox I add.)

using System;
using System.Drawing;
using System.Windows.Forms;

namespace Outlines {

    public partial class Form1 : Form {

        public MyPictureBox MPB;

        public Form1() {
            InitializeComponent();
            MPB = new MyPictureBox("Benny.png");
            this.Controls.Add(MPB);
        }

        private void Form1_Load(object sender, EventArgs e) {
            Console.WriteLine("Form1:Load");
        }

        protected override void OnResizeEnd(EventArgs e) {
            Console.WriteLine("Form1:ResizeEnd");
            base.OnResizeEnd(e);
            MPB.Size = new Size(this.ClientRectangle.Width, this.ClientRectangle.Height);
            this.Invalidate(true);
        }

        protected override void OnClick(EventArgs e) {
            Console.WriteLine("Form1:OnClick");
            base.OnClick(e);
            this.Invalidate(true);
        }

        protected override void OnPaint(PaintEventArgs e) {
            Console.WriteLine("Form1:OnPaint");
            base.OnPaint(e);
        }

    }

    public class MyPictureBox : PictureBox {

        private Bitmap _bitmap;

        public MyPictureBox(string pathName) {
            _bitmap = new Bitmap(pathName);
            this.Size = new Size(500, 500);
            this.Enabled = true;
            this.Visible = true;
        }

        protected override void OnPaint(PaintEventArgs pe) {
            Console.WriteLine("MPB:OnPaint");
            base.OnPaint(pe);
            var graphics = this.CreateGraphics();
            graphics.Clear(Color.Gray);
            if (_bitmap == null)
                return;
            graphics.DrawImage(_bitmap, new Point(0, 0));
            graphics.Dispose();
        }

        protected override void OnResize(EventArgs e) {
            Console.WriteLine("MPB:OnResize");
            base.OnResize(e);
        }

    }

}

Upvotes: 0

Views: 53

Answers (1)

BoCoKeith
BoCoKeith

Reputation: 946

Don't create a new graphics object inside the OnPaint method; use the one that is provided in the PaintEvents argument. As @Jimi points out above...

Control.CreateGraphics(); is used in specific, defined, situations (to measure stuff, mostly). Don't use it to draw and never store it (it will be invalid as soon as the Control is repainted - this happens constantly). Always paint in the overridden OnPaint() method or the Paint event handler (or DrawItem and friends) using the Graphics object provided (as PaintEventArgs).

Upvotes: 1

Related Questions