Reputation: 103
IDE: Microsoft Visual Studio 2010 Platform : C#.Net
I am trying to call paint event inside a function in one of my forms in C#. The function is currently having two integer arguments, but I want the paint event of a panel to be called in that function, but I am getting error while calling the paint event. Any suggestions ?
Upvotes: 0
Views: 1663
Reputation: 326
None of the previous answers worked for me. After a while investigating, I have managed to raise paint event with the following instruction:
this.InvokePaint(this, new PaintEventArgs(this.CreateGraphics(), this.DisplayRectangle));
Upvotes: -1
Reputation: 941218
Getting the Paint event handler to run just requires telling Winforms that the panel needs to be repainted:
panel1.Invalidate();
You can also use Refresh(), that calls the Paint event immediately rather than letting Windows sort out the best time to generate the event. Which is when nothing more pressing needs to be done, like responding to user input or dispatching messages that are sent instead of posted. Not something you should ever consider, although it is a band-aid for not using a thread.
Upvotes: 1
Reputation: 1098
You should save the coordinates to a field or list, what ever makes more sense for your case.
And then Invalidate the Panel, this will Raise the Paint Event, in which you will then be able to draw your line from the saved coordinates.
This is the only way to get what you most likely want without alot of trouble, because drawing to a window(Panel) in a non Standard way is not an easy Task to do.
[EDIT] Also: Don't Forget you have to redraw the entire "Scene" on that Panel every time the Paint Event is raised, even if you use a Bitmap (backbuffer) as a backup, you need to blit this Bitmap onto the Panel again.
[EDIT] Sample:
private readonly Stack<Point> _points = new Stack<Point>();
private readonly Pen _blackPen = new Pen(Color.Black);
private void Form1_Paint(object sender, PaintEventArgs e)
{
var points = _points.ToArray();
for (int i = 1; i < points.Length; i++)
{
e.Graphics.DrawLine(_blackPen, points[i - 1], points[i]);
}
}
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
_points.Push(e.Location);
Invalidate();
}
Upvotes: 1