I want to add some detail and a fix to the code provided by Simon.
For example, add the following code to the form's constructor:
this.Paint += (sender, eventArgs) => {
using (Pen pen = Pen(Color.FromArgb(255, 255, 0, 0))) {
eventArgs.Graphics.DrawLine(pen, startX, startY, endX, endY);
}
};
Pay attention for the "using" statement. It's used to guarantee disposal of
pen
, no matter if exception was thrown or not. This construct is a syntactic sugar and is strictly equivalent to placing creation of the
pen
under
try-finally
block with disposal operation in the
finally
part.
Alternatively, you can re-use the
pen
and other resources. In this case, you should created them in the form's constructor and dispose in
Form.Dispose
, see
http://msdn.microsoft.com/en-us/library/aw58wzka.aspx[
^].
You need to initialize geometric parameters
startX, startY, endX, endY
prior to the call. If you ever need to change the position of the line, make the form fields. To change the position of line, you need to change the values of those fields. Now, how to trigger re-drawing of the picture? You need to cause sending the event
WM_PAINT
to the form. This is done using
Form.Invalidate
(inherited from
Control.Invalidate
. You can improve performance using
Invalidate
with parameters (
Rectangle
or
Region
) to invalidate just some part of the scene.
—SA