How to call paint event from a button click event?

大城市里の小女人 提交于 2019-12-13 04:48:02

问题


I have a pictureBox with the event "paint" and I also got code in there to draw graphics.

such as:

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

    private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        Graphics graphics = e.Graphics;
        graphics.DrawEllipse(Pens.Blue, 10, 10, 100, 100);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        pictureBox1.Invalidate();
    }
}

}

My question is. How to fire these events of from a button_click event? I searched alot on the web and found alot of awnsers like ".invalidate()" or ".Refresh()" and ".Update". But my assignment tells me that I need to do it with the .Refresh() method and the painting needs to be in a pictureBox.

What I notice from .Refresh() method. Is that it erases the pictureBox(draws the pictureBox how it was created on initialize). So firing off .Refresh method in a button did not work for me.

Any other suggestions how to fire off a paint event from a button?


回答1:


This should do the trick:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        pictureBox1.Image = new Bitmap(pictureBox1.Width, pictureBox1.Height);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        using (var g = Graphics.FromImage(pictureBox1.Image))
        {
            g.DrawEllipse(Pens.Blue, 10, 10, 100, 100);
            pictureBox1.Refresh();
        }
    }
}


来源:https://stackoverflow.com/questions/27766600/how-to-call-paint-event-from-a-button-click-event

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!