Home > Enterprise >  C# Draw on PictureBox with Graphics.DrawLine() not working on Paint event
C# Draw on PictureBox with Graphics.DrawLine() not working on Paint event

Time:10-15

I have a from with a PictureBox and a button (see image). enter image description here

When user click on "Draw" the programm draws two crosses.

I did the same thing for the PictureBox Paint event handler, but if I minimize the form and reopen it nothing is drawn (except Image property of picture box): enter image description here

Code:

 public partial class Form1 : Form
{

    Point[] points = new Point[2];
    Graphics g;
    public Form1()
    {
        InitializeComponent();
        points[0] = new Point(50, 50);
        points[1] = new Point(100, 100);
        g = pictureBox1.CreateGraphics();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        DrawCrosses(points);
    }

    private void DrawCrosses(Point[] points)
    {
        
        Pen pen = new Pen(Color.Red)
        {
            Width = 2
        };
        foreach (Point p in points)
        {
            Point pt1 = new Point(p.X, p.Y - 10);
            Point pt2 = new Point(p.X, p.Y   10);
            Point pt3 = new Point(p.X - 10, p.Y);
            Point pt4 = new Point(p.X   10, p.Y);
            g.DrawLine(pen, pt1, pt2);
            g.DrawLine(pen, pt3, pt4);
        }
    }

    private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        DrawCrosses(points);
    }
}

CodePudding user response:

You should not create a new Graphics object in the event handler.

You should use the one passed from event

    public partial class Form1 : Form
    {

        Point[] points = new Point[2];
        public Form1()
        {
            InitializeComponent();
            points[0] = new Point(50, 50);
            points[1] = new Point(100, 100);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            DrawCrosses(points, pictureBox1.CreateGraphics());
        }

        private void DrawCrosses(Point[] points, Graphics g)
        {

            Pen pen = new Pen(Color.Red)
            {
                Width = 2
            };
            foreach (Point p in points)
            {
                Point pt1 = new Point(p.X, p.Y - 10);
                Point pt2 = new Point(p.X, p.Y   10);
                Point pt3 = new Point(p.X - 10, p.Y);
                Point pt4 = new Point(p.X   10, p.Y);
                g.DrawLine(pen, pt1, pt2);
                g.DrawLine(pen, pt3, pt4);
            }
        }

        private void pictureBox1_Paint(object sender, PaintEventArgs e)
        {
            DrawCrosses(points, e.Graphics);
        }
    }
  • Related