user3824825
user3824825

Reputation: 53

very simple program to draw a filled rectangle .. why it does not work ?

I am new with using graphics and I am trying to draw a filled rectangle when the form opens.. but nothing is working and do not know the reason

here is my code :

private void Result_Load(object sender, EventArgs e)
{
    System.Drawing.SolidBrush myBrush = new       System.Drawing.SolidBrush(System.Drawing.Color.Green);
    System.Drawing.Graphics formGraphics = this.CreateGraphics();
    formGraphics.FillRectangle(myBrush, new Rectangle(0, 0, 200,300));
    myBrush.Dispose();
    formGraphics.Dispose();
}

where Result is my form that is supposed I draw the rectangle on when it is loaded

but when I load the form nothing happens at all

where the problem ?

thanks in advance

Upvotes: 0

Views: 1079

Answers (1)

General-Doomer
General-Doomer

Reputation: 2761

Add handler to Paint event in form's constructor:

/// <summary>
/// form constructor
/// </summary>
public frmMain()
{
    InitializeComponent();

    this.Paint += frmMain_Paint;
}

And create method frmMain_Paint:

void frmMain_Paint(object sender, PaintEventArgs e)
{
    using (System.Drawing.SolidBrush myBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Green))
    {
        e.Graphics.FillRectangle(myBrush, new Rectangle(0, 0, 200, 300));
    }
}

Tips

  1. Use e.Graphics to draw (not this.CreateGraphics())
  2. Use using keyword as in example above.

Upvotes: 3

Related Questions