调用函数时画线

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);
}

如果我执行这段代码,什么也不会发生。

我不想使用 Form1_Paint 事件,因为我只能在开始时调用它!?

我想画一条线,想画多少次就画多少次 例如我用点填充 2 Textboxes,然后单击 Button 并绘制一条线。

您必须使用 FormPaint 或类似的方法。 很多原因 重新绘制表单(这就是为什么 FormLoad 是一个错误的地方:如果表单改变其大小,最大化等它将被重新绘制并且行会消失)。相反 Paint 在表单被绘制时触发 - 进行额外绘制的最佳位置:

  // 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(); 
  }