Home > front end >  Can't draw with CreateGraphics
Can't draw with CreateGraphics

Time:05-30

I just have a Panel and want to draw on it. Without the use of its Paint event. So i tried this and it doesn't work.

private void Form1_Load(object sender, EventArgs e)
{
    Graphics g = panel1.CreateGraphics();
    g.DrawRectangle(Pens.Black, 0, 0, 10, 10);
}

If someone could provide me with explonation and example code that would be nice.

CodePudding user response:

You use CreateGraphics to paint something in a synchronous way. For example, to paint in a Bitmap and save it to disk. May be a better way if you add an event handler to Paint event of your panel, in the designer or in form constructor:

panel1.Paint  = this.OnPanel1_Paint;

And paint in that event:

private void OnPanel1_Paint(object sender, PaintEventArgs e)
{
    var g = e.Graphics;
    g.DrawRectangle(Pens.Black, 0, 0, 10, 10);
}

You don't need dispose this graphics here, only paint that you want.

In this way, when you need force the repaint (for example, you add another rectangle on every click in the panel) you must invoke panel1.Invalidate();. This method tell to Windows that you need repaint the control and Windows invoke the event as soon as possible. Obviously, you need to know what to draw and it's depends of your application. You can have a List of rectangles and add a new rectangle on each click. Then, in OnPanel1_Paint method, you draw all your list rectangles.

CodePudding user response:

Your form is not visible while it fires Load event. You should draw the rectangle after the form becomes visible. A solution would be to add a button on your form. You can name it drawRectangleButton. Then subscribe to its click event and draw.

private void drawRectangleButton_Click(object sender, EventArgs e)
{
    Graphics g = panel1.CreateGraphics();
    g.DrawRectangle(Pens.Black, 0, 0, 10, 10);
}
  • Related