A question regarding to drawing in C#

Y

Yuelin

Hi, thanks for the answers to my previous questions.

Now I have a question on drawing in C#:

For example I have written following code to draw a rectangle on a form:

protected override void OnPaint ( PaintEventArgs e)
{
Graphics dc = e.Graphics;
Pen BluePen = new Pen(Volor.Blue, 3);
dc.DrawRectangle(BluePen, 0, 0, 50, 50);
base.OnPaint (e);
}

The reason I put the code in this method instead of puting it into the
constructor is that
I want to move and redraw the rectangle later. Also is it is because if I
put the drawing code in the
constructor the rectangle would be "erased" when I move another window (say,
Task Manager)
over the rectangle.

Now I want to re-position the rectangle, say move to (10, 20), whenever I
click it.
Presumebly I should put the code for redrawing into the following method:

private void OnMouseDownEvent(object sender, MouseEventArgs e)

But how can I call the OnPaint method from the OnMouseDownEvent method?

Anyone has ideas? Thanks.

Yuelin
 
N

Noah Coad [.NET/C# MVP]

Hello Yuelin,

Well you need to store the location to draw the rectangle in a variable in
the "MouseDown" event. Then call "this.Invalidate()" which will invalidate
the graphics of the control causing them to be redrawn.

This is used so that if the control does not need to be redrawn at this time
(it is minimized or another control/form is on top), then the system does
not waste resources redrawing the control until it is visible to the user.

Good luck!
-Noah Coad
Microsoft MVP & MCP [.NET/C#]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top