Hi guys. You've helped me out a lot in the past, for which I am very grateful. Right now however, I am banging my head against the wall, because I simply cannot get my head around drawing simple shapes!

The current code results in well... Nothing whatsoever. My form is as blank as it ever was.

public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            initNewGame();
        }
        private void drawPoint(int x_,int y_){
            Graphics g = Graphics.FromHwnd(this.Handle);
            SolidBrush brush = new SolidBrush(Color.LimeGreen);
            Point dPoint = new Point(x_, (this.Height - y_));
            dPoint.X = dPoint.X - 2;
            dPoint.Y = dPoint.Y - 2;
            Rectangle rect = new Rectangle(dPoint, new Size(4, 4));
            g.FillRectangle(brush, rect);
            g.Dispose();
        }
        private void initNewGame()
        {
            this.drawPoint(50, 50);
        }
    }

Any ideas of how to hammer this into working order?

That is not the right way. You can put the code in Form_Shown event and it'll work, but the rectangle will be erased if the form is minimized, resized etc.

The correct way is to use Form_Paint event.

Change the drawPoint() method and add a new parameter for Graphics:

private void drawPoint([B]Graphics g[/B], int x_,int y_){
    SolidBrush brush = new SolidBrush(Color.LimeGreen);
    Point dPoint = new Point(x_, (this.Height - y_));
    dPoint.X = dPoint.X - 2;
    dPoint.Y = dPoint.Y - 2;
    Rectangle rect = new Rectangle(dPoint, new Size(4, 4));
    g.FillRectangle(brush, rect);
}

Add Paint event for the Form and call the drawPoint method:

private void Form1_Paint(object sender, PaintEventArgs e)
{
    drawPoint(e.Graphics, 10, 10);
}

Hope that helps.

Thanks

Edited 6 Years Ago by farooqaaa: n/a

Comments
Good explanation..

That does work. However what I want to know is why. And how can I get Form1_Paint to be run at runtime (say, every time I want a new rectangle on the screen!). Maybe I want it draw the rectangle when I click a button. It should be possible.

PS: Sorry for late response + necroing thread. Was away.

Use the forms Invalidate or Refresh methods in your Button Click handler.
These methods will somehow call your Form1_Paint method.

This article has been dead for over six months. Start a new discussion instead.