C# Forms - Using Paint methods?

2019-08-02 18:55发布

问题:

In c# forms I have created a new paint method:

private void thisPolygon(PaintEventArgs e)
{
    Pen clrBlue = new Pen(Color.Blue, 3);
    Point[] Wst = new Point[5];
    Wst[0] = new Point(20, 350);
    Wst[1] = new Point(110, 200);
    Wst[2] = new Point(200, 190);
    Wst[3] = new Point(210, 275);
    Wst[4] = new Point(190, 400);
    Wst[5] = new Point(50, 390);
    e.Graphics.DrawPolygon(clrBlue, Wst);
}

Now, how do I call it? I can't make it work, this doesn't work:

private void Form1_Load(object sender, EventArgs e)
{
    thisPolygon(); ///I've tried adding some stuff in brackets area, failed.
}

回答1:

You have a few different problems.

(1) Array Capacity. Your array is initialized with 5 storage locations, but you are attempting to set a sixth value.

Point[] Wst = new Point[5]; // 5 indexes
...
Wst[5] = new Point(50, 390); // Tries to access a sixth, but is out of bounds

Change this to.

Point[] Wst = new Point[6];

Remember that arrays are zero-based indexed.

(2) Not using OnPaint. You're calling thisPolygon in the OnLoad method, which won't persist your drawing. Move your call to the OnPaint method of the form.

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

(3) Not passing PaintEventArgs. You're not passing in any event arguments to your thisPolygon method, and it won't even compile as it is. Pass in the paint arguments from the OnPaint method.

protected override void OnPaint(PaintEventArgs e) {
    base.OnPaint(e); // Pass in e
    thisPolygon();
}