You approach is almost correct, but you should fix your logic and problems in the code. In brief, you should do all rendering in your handler of your
Paint
event. First, you draw the background image, and, on top if it, you draw your mouse-generated line from data. The mouse events only manipulate data and call
Invalidate
.
Your performance can be improved by calling
Invalidate
with a parameter (
Rectangle
or
Region
) — it will trigger re-rendering of only the part of the scene.
Also, I must say you don't need the
Panel
. You should better derive a custom control from
Control
and override
OnPaint
instead of using
Paint
event. Don't worry, you will need to resort to a derived control anyway. Why? Because you also need to add double buffering, but to do that, you will need to access the protected method
SetStyles
.
You will need to add the styles
System.Windows.Forms.ControlStyles.AllPaintingInWmPaint | System.Windows.Forms.ControlStyles.OptimizedDoubleBuffer
. This is important to avoid flicker.
See:
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.setstyle.aspx[
^],
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.aspx[
^],
http://msdn.microsoft.com/en-us/library/system.windows.forms.controlstyles.aspx[
^].
You also need to fix your code style, naming, etc.
—SA