C#Windows窗体,行不会绘制!画布未定义

问题描述

在第27行定义“画布”需要什么?我到处都看过了,但是它只给出为什么可能未定义对象的原因,而不是为什么未定义特定对象画布的原因。有人可以告诉我我在想什么吗?


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

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

        private void Form1_Load(object sender,EventArgs e)
        {

        }

        private void canvas_Paint(object sender,PaintEventArgs e)
        {
            Graphics gObject = canvas.CreateGraphics();

            Brush red = new SolidBrush(Color.Red);
            Pen redPen = new Pen(red,8);

            gObject.DrawLine(redPen,10,35,500);
        }
    }
}

解决方法

canvas必须是表单中的控件。您必须将其添加到设计器中,并为其命名canvas。哪一种?嗯...我想说一个PictureBox。

您还需要从属性面板(“事件”标签)将Paint事件链接到canvas_Paint。是的,e.Graphics比使用CreateGraphics更为可取。

您从哪里获得该代码?