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
事件,因为我只能通过Start来调用它?
我想在我想要的时候画一条线,我想要的地方和我想要的次数
例如我用点数填充2 Textbox
es然后点击Button
并绘制一条线。
答案 0 :(得分:3)
您必须使用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();
}