Gyorgy
Gyorgy

Reputation:

PictureBox resize & paint problem

I want to show some graphics in a Winform app, it will be a stock's chart drawing tool. I think (but I am not sure...) I have to use a PictureBox, and using the System.Drawing.Graphics class' drawing primitives to draw the chart. I have started coding it, now it works more-or-less, but I have a problem with the resizing feature, as follows: when I resize the entire form, I see that the program shows the graphics then inmediately clear it. When I stop the mouse movement (without to release the mouse button) the graphics disappears!?!?

I made a small test environment to demo the bug: Using VS2005, creating a new C# Windows Forms app, adding only a PictureBox to the form. Setting the PictureBox's anchor to left, top, right and bottom. Add two event handler, the Resize to the PictureBox, and the Paint to the Form.

namespace PictureBox_Resize {
public partial class Form1 : Form {
    public Form1() {
        InitializeComponent();
        Ellipse_Area = this.pictureBox1.Size;
    }

    private Pen penBlack = new Pen(Color.Black, 1.0f);
    private Size Ellipse_Area;

    private void Form1_Paint(object sender, PaintEventArgs e) {
        Graphics g = this.pictureBox1.CreateGraphics();

        g.DrawEllipse(penBlack, 0, 0, Ellipse_Area.Width, Ellipse_Area.Height);
    }

    private void pictureBox1_Resize(object sender, EventArgs e) {
        Control control = (Control)sender;
        Ellipse_Area = control.Size;
        this.pictureBox1.Invalidate();
    }
}

}

This small app shows the problem. It only draws an ellipse, but of course my drawing code is much more complicated one...

Any idea why the ellipse disappears when I resize the Form????

Upvotes: 2

Views: 9945

Answers (2)

Mark Heath
Mark Heath

Reputation: 49482

Why are you using a PictureBox? I would create a UserControl for your chart and draw the ellipse in its Paint method, just using its current size. In its constructor, set it up for double buffering and all painting in the paint method.

this.SetStyle(ControlStyles.DoubleBuffer | 
  ControlStyles.UserPaint | 
  ControlStyles.AllPaintingInWmPaint,
  true);

Upvotes: 6

Gambrinus
Gambrinus

Reputation: 2136

As far as I remember from my C++ days - where I did loads of such image-stuff - you need to call the repaint method - or override it to fit it for your behaviour.

Upvotes: 1

Related Questions