views:

2976

answers:

2

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????

A: 

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.

Gambrinus
+1  A: 

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);
Mark Heath
Why I use the PictureBox? Because it seemed to me logical using "PictureBox" to beeing the container for pictures and graphics. It has CreateGraphics() and the help of the Graphics class I can draw onto the Form.
but the point of PictureBox is to display an image file such as a .png or a .jpg. You want to draw your own graphics. You can get hold of a Graphics object on any control.
Mark Heath