ExoSkull
ExoSkull

Reputation: 9

C# How do I draw a line between two objects on a windows form?

I've been trying to draw a line between two objects for a long time now, but it still won't work.

My program is supposed to make two picture boxes (Already made, called PB1 and PB2) and connect them with a line on the form.

I have this:

public void DrawStuff(object sender, PaintEventArgs e)
    {
        Pen blackPen = new Pen(Color.Black, 3);
        Point point1 = new Point(PB[0].Location.X, PB[0].Location.Y);
        Point point2 = new Point(PB[1].Location.X, PB[1].Location.Y);

        e.Graphics.DrawLine(blackPen, point1, point2);
        CreateGraphics();
    }

But I can't call the function! Also, the Boxes are being created with a button, so it can't draw from the start, it has to do it after I push that button. If anyone has a working code, please let me know, I'm about to break down.

Upvotes: 0

Views: 2051

Answers (1)

dotNET
dotNET

Reputation: 35400

  1. Do not (read NEVER EVER) call CreateGraphics() explicitly. This is a crime against humanity, except for very rare situations.
  2. Handle Paint event (or override OnPaint()) of your Form. Write your line drawing code in there.

Something like this:

protected override void OnPaint(PaintEventArgs e)
{
  base.OnPaint(e);

  using(var blackPen = new Pen(Color.Black, 3))
    e.Graphics.DrawLine(blackPen, PB[0].Location, PB[1].Location);
}
  1. Whenever you need to refresh screen manually, call this.Invalidate().

Upvotes: 1

Related Questions