Yes, you can use Graphics outside of your Paint/PaintBackground events, but you shouldn't need to, nor is it advised.
My guess is (given that you referenced MouseMove) that you want some painting to occur when particular events occur on the control; there are a couple of solutions to this:
- Subclassing (greater control over your component, control reuse etc)
- Registering event handlers (good for quick and dirty implementation)
Example 1 - registering event handlers
private void panel1_MouseMove(object sender, EventArgs e)
{
// forces paint event to fire for entire control surface
panel1.Refresh();
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.....;
}
Example 2 - subclassing
class CustomControl : Control
{
public CustomControl()
{
SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintInWmPaint | ControlStyles.ResizeRedraw | ControlStyles.OptimizedDoubleBuffer, true);
UpdateStyles();
}
protected override void OnMouseMove(EventArgs e)
{
base.OnMouseMove(e);
Refresh();
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
e.Graphics...;
}
}
Notes
- Once
OnPaint/Paint has been called, e.Graphics will be disposed, therefore, setting a global reference to that object will be useless since it will be null once your Paint event has completed.
- You can use
CreateGraphics() if you absolutely need Graphics outside of your Paint/PaintBackground methods/events, but this isn't advised.
Paint/PaintBackground fall naturally into the WinForms event/rendering pipeline, so you should ideally override these and use them appropriately.