You have at least 2 solutions: 1. Create a class that extends PictureBox (or Control if you get adventurous) and override OnPaint(). 2. Keep a copy of the image in memory. I think the 1st option is the better choice because it opens the possibility for code-reuse and uses less memory. Example:
public class PictureSelectionBox : PictureBox
{
private Rectangle selectionRect;
private Pen selectionPen;
public Rectangle CurrentSelection
{
get { return this.selectionRect; }
set
{
this.selectionRect = value;
this.Refresh();
}
}
public Pen SelectionPen
{
get { return this.selectionPen; }
set
{
this.selectionPen = value;
this.Refresh();
}
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
if (this.selectionPen != null &&
this.selectionRect.Width != 0 &&
this.selectionRect.Height != 0)
{
e.Graphics.DrawRectangle(this.selectionPen, this.selectionRect);
}
}
public void CommitSelection()
{
Graphics g = Graphics.FromImage(base.Image);
g.DrawRectangle(this.selectionPen, this.selectionRect);
g.Dispose();
this.CurrentSelection = new Rectangle(0, 0, 0, 0);
this.Refresh();
}
}
You could even override the OnMouseDown, OnMouseMove, and OnMouseUp events in the derived class to allow the user to make his/her selection. You better watch out with the use of Refresh() doing this though because you'll get some ugly flickering. I'd either [DllImport] InvalidateRect() or something like:
Graphics g = this.CreateGraphics();
OnPaint(new PaintEventArgs(g, this.ClientRectangle));
g.Dispose();
Enjoy, David