问题
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