You need to handle four events, either for the Form you want to draw on, or a Panel instead:
MouseDown
MouseMove
MouseUp
Paint
Declare three class level variables:
private bool drawBox = false;
private Point start;
private Point end;
Handle the Paint event:
private void myPanel_Paint(object sender, PaintEventArgs e)
{
if (start != null && end != null)
{
int mnX = Math.Min(start.X, end.X);
int mnY = Math.Min(start.Y, end.Y);
int mxX = Math.Max(start.X, end.X);
int mxY = Math.Max(start.Y, end.Y);
e.Graphics.DrawRectangle(Pens.Black, mnX, mnY, mxX - mnX, mxY - mnY);
}
}
And handle the mouse events:
private void myPanel_MouseDown(object sender, MouseEventArgs e)
{
drawBox = true;
start = e.Location;
end = start;
myPanel.Invalidate();
}
private void myPanel_MouseMove(object sender, MouseEventArgs e)
{
if (drawBox)
{
end = e.Location;
myPanel.Invalidate();
}
}
private void myPanel_MouseUp(object sender, MouseEventArgs e)
{
drawBox = false;
}