Click to See Complete Forum and Search --> : drawing in win form


john_avi
February 17th, 2009, 12:14 AM
Hi All,
I am new to c# .net programming. I am making an application where I have to draw some shapes on win forms. I want to draw it after "draw" button is clicked. I tried to draw it using Graphics object. But its not appearing. I am attaching sample code.

private void DrawClicked(object sender, EventArgs e)
{
//location of "draw" button
Point ptBtn = buttonDraw.Location ;
int xCord = ptBtn.X;
int yCord = ptBtn.Y;

//location of win form
Point ptDlg = this.Location;
int xStart = ptDlg.X;
int yStart = ptDlg.Y;

//size of "draw" button.
int ibtnWidth = buttonDraw.Width ;
int btnHt = buttonDraw.Height ;

Graphics drawObj = buttonDraw.CreateGraphics();
Pen blackPen = new Pen(Color.Black, 3);
drawObj.DrawPie(blackPen, xStart + yCord, yCord + yStart + btnHt+10, 50, 50, 0, 30);

}


In this form, I have empty space below "draw" button and I want to draw below that button.
can somebody help me what is wrong with above code

BigEd781
February 17th, 2009, 12:21 AM
If you would like to paint a control, you should override the OnPaint method of the canvas object and paint there. You can call Invalidate() when you need to cause a re-paint. Currently you are calling CreateGraphics() on the button, so your drawing surface is the button itself. Also, your arguments to DrawPie are strange. I haven't used it in a while, but I believe that it takes a start angle and a number representing the number of degrees to draw.

john_avi
February 17th, 2009, 12:51 AM
I have given some hard coded values for start angle and end angle. But I want to draw it after the "draw" button is clicked so how can I get a graphics object inside draw click event handler which will let me draw inside the client area of dialog.

BigEd781
February 17th, 2009, 12:55 AM
You don't. You override the OnPaint method of your class and put the drawing logic there. When you need to repaint, call Invalidate() on your control.

john_avi
February 17th, 2009, 01:12 AM
then i"ll have to keep a switch case in onpaint() for different buttons clicked and different shapes drawing. which does not seem to be a fair solution.

BigEd781
February 17th, 2009, 01:18 AM
then i"ll have to keep a switch case in onpaint() for different buttons clicked and different shapes drawing. which does not seem to be a fair solution.

Well, your model is not great, so that is why you need the switch statement, not because of some deficiency in how painting is supposed to be done in .NET. Click a button and paint on a form is overly simplistic. A real graphics application would be much more complex than that.

john_avi
February 17th, 2009, 01:29 AM
ok thanks for the help.