Search code examples
c#.netsystem.drawing

DrawLine on calling a function


private void Form1_Load (object sender, EventArgs e)
{
    Point p1 = new Point (300, 300);
    Point p2 = new Point (120, 120);      

    DrawLine(p1, p2);            
}

private void DrawLine(Point p1, Point p2)
{
    Graphics g = this.CreateGraphics();
    Pen blackPen = new Pen(Color.Black, 1);
    g.DrawLine(blackPen, p1, p2);
}

If I execute this Code, nothing happens.

I don't want to use the Form1_Paint event because I can only call this by the Start!?

I want to draw a Line when I want and where I want and as many times as I want e.g. I fill 2 Textboxes with Points and then I click a Button and it draws a line.


Solution

  • You have to use FormPaint or similar approach. There are many reasons for forms being repainting (and that's why FormLoad is a wrong place: if the form change its size, be maximized etc it'll be repainted and the line'll vanish). On the contrary Paint fires when form has been painted - the best place to do an additional painting:

      // What to paint: a line [m_FromPoint..m_ToPoint] 
      private Point m_FromPoint = new Point (300, 300);
      private Point m_ToPoint = new Point (120, 120); 
    
      // Painting itself: whenever form wants painting...
      private void Form1_Paint(object sender, PaintEventArgs e) {
        // ... draw an additional line
        e.Graphics.DrawLine(Pens.Black, m_FromPoint, m_ToPoint);
      }
    
      // Change painting (on button1 click)
      private void button1_Click(object sender, EventArgs e) {
        // We want a different line...
        m_FromPoint = ... //TODO: put the right point here 
        m_ToPoint = ...   //TODO: put the right point here 
    
        // ...and we want it at once - force repainting
        Invalidate();
        Update(); 
      }