Generalmente si eseguono tutti i disegni nel gestore eventi vernice. Se si desidera eseguire un aggiornamento (se un utente fa clic sul pannello per esempio), è necessario rimandare l'azione: si memorizzano i dati richiesti (coordinate su cui l'utente ha fatto clic) e impongono un ridisegno del controllo. Ciò causa l'attivazione dell'evento paint, in cui è possibile disegnare le cose memorizzate in precedenza.
Un altro modo sarebbe (se si vuole veramente disegnare al di fuori del gestore di eventi 'panel1_Paint') per disegnare all'interno di un'immagine del buffer e copiare l'immagine nell'oggetto di grafica dei controlli nel gestore di eventi paint.
Aggiornamento:
Un esempio:
public class Form1 : Form
{
private Bitmap buffer;
public Form1()
{
InitializeComponent();
// Initialize buffer
panel1_Resize(this, null);
}
private void panel1_Resize(object sender, EventArgs e)
{
// Resize the buffer, if it is growing
if (buffer == null ||
buffer.Width < panel1.Width ||
buffer.Height < panel1.Height)
{
Bitmap newBuffer = new Bitmap(panel1.Width, panel1.Height);
if (buffer != null)
using (Graphics bufferGrph = Graphics.FromImage(newBuffer))
bufferGrph.DrawImageUnscaled(buffer, Point.Empty);
buffer = newBuffer;
}
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
// Draw the buffer into the panel
e.Graphics.DrawImageUnscaled(buffer, Point.Empty);
}
private void button1_Click(object sender, EventArgs e)
{
// Draw into the buffer when button is clicked
PaintBlueRectangle();
}
private void PaintBlueRectangle()
{
// Draw blue rectangle into the buffer
using (Graphics bufferGrph = Graphics.FromImage(buffer))
{
bufferGrph.DrawRectangle(new Pen(Color.Blue, 1), 1, 1, 100, 100);
}
// Invalidate the panel. This will lead to a call of 'panel1_Paint'
panel1.Invalidate();
}
}
Ora le immagini tratte wont essere persi, anche dopo un ridisegno del controllo, perché attira solo il buffer (l'immagine, salvato nella memoria). Inoltre puoi disegnare le cose ogni volta che si verifica un evento, semplicemente attingendo al buffer.
fonte
2010-04-09 23:45:14
Utilizzi WinForms? O WPF? – Vlad
Sto usando WinForms. – Lisa
Perché vuoi metterlo da qualche altra parte e non nel gestore di eventi vernice? –