I need draw a rectangle only inside of picturebox with mousemove. without exceeding border the picturebox.
Dragging to the right or down works fine for me... How to make moviment reverse ?
My code below.
Rectangle Rect = new Rectangle();
private Point RectStartPoint;
public Pen cropPen = new Pen(Color.Red, 2);
public Form1()
{
InitializeComponent();
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
RectStartPoint = e.Location;
picImagem.Invalidate();
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Left)
{
Point tempEndPoint = e.Location;
Rect.Location = new Point(Math.Min(RectStartPoint.X, tempEndPoint.X),
Math.Min(RectStartPoint.Y, tempEndPoint.Y));
Rect = new Rectangle(
Math.Min(tempEndPoint.X, Rect.Left),
Math.Min(tempEndPoint.Y, Rect.Top),
Math.Min(e.X - RectStartPoint.X, picImagem.ClientRectangle.Width - RectStartPoint.X),
Math.Min(e.Y - RectStartPoint.Y, picImagem.ClientRectangle.Height - RectStartPoint.Y));
picImagem.Refresh();
picImagem.CreateGraphics().DrawRectangle(cropPen, Rect);
}
}