carreter
carreter

Reputation: 60

C# Line Painting Problems

I need help drawing a line on a WinForm.

The code I currently have is mostly pulled off of MSDN:

using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace BouncingBall
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        this.Invalidate();
    }
    private void Form1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
    {

        // Insert code to paint the form here.
        Pen pen = new Pen(Color.FromArgb(255, 0, 0, 0));
        e.Graphics.DrawLine(pen, 10, 10, 300, 200);
    }
}

}

Currently, this code does not draw anything at all.

Upvotes: 0

Views: 501

Answers (2)

vcsjones
vcsjones

Reputation: 141678

Your code, as posted, is fine. It renders a black line in the middle of the form:

enter image description here

I suspect your problem is you don't have the form's Paint event subscribing to your Form1_Paint method. You can't just put this method there and expect it to get called magically.

You can fix that by adding it to your Form's constructor:

public Form1()
{
    InitializeComponent();
    this.Paint += Form1_Paint;
}

Alternatively, you can do this in the designer, which does the same event subscription, it just tucks it away inside of InitializeComponent().

Upvotes: 1

PaulG
PaulG

Reputation: 7132

According to MSDN:

using System.Drawing;

Pen myPen;
myPen = new Pen(System.Drawing.Color.Red);
Graphics formGraphics = this.CreateGraphics();
formGraphics.DrawLine(myPen, 0, 0, 200, 200);
myPen.Dispose();
formGraphics.Dispose();

Your code actually looks fine, are you sure that method is firing?

Upvotes: 0

Related Questions