在表单加载上使用System.Drawing.Graphics绘画

时间:2017-10-11 23:21:24

标签: c# winforms system.drawing.graphics

我试图在C#Windows窗体中使用System.Drawing.Graphics绘制一个矩形,但如果不使用按钮点击事件,我似乎无法使其工作。

在线搜索发现我必须在表单中使用Paint或Shown事件,但是我的尝试都没有成功。

我想在加载表单及其组件时运行我的Draw()方法。

public Form1()
{
    InitializeComponent();
    Draw(); //doesn't work
}

private void Draw()
{
    Graphics g = pictureBox.CreateGraphics();
    g.Clear(Color.White);
    Pen p = new Pen(Color.Black, 1);
    g.DrawRectangle(p, 0, 0, 50, 50);
}

private void ApproximateButton_Click(object sender, EventArgs e)
{
    Draw(); //works
}

实现这一目标的正确方法是什么?

2 个答案:

答案 0 :(得分:1)

您可以实现此操作覆盖Form的OnLoad事件,也可以重用PaintEvent参数。

protected override void OnPaint(PaintEventArgs e)
{
    base.OnPaint(e);
    using (Graphics g = e.Graphics)
    {
        g.Clear(Color.White);
        using (Pen p = new Pen(Color.Black, 1))
        {
            g.DrawRectangle(p, 0, 0, 50, 50);
        }
    }
}

编辑:添加using处理资源的声明

答案 1 :(得分:0)

您也可以将您的功能置于Form1' Load事件下。

订阅Load活动后,试试这个;

public Form1()
{
    InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
    Draw();
}

private void Draw()
{
    Graphics g = pictureBox.CreateGraphics();
    g.Clear(Color.White);
    Pen p = new Pen(Color.Black, 1);
    g.DrawRectangle(p, 0, 0, 50, 50);
}
在构造函数之后调用

Load事件。您的表单元素正在构造函数中创建,因此您在尝试在同一函数中使用它们时遇到一些问题。