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.
Your code, as posted, is fine. It renders a black line in the middle of the form:
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()
.