0

I have this problem. I used code bellow (by Erno de Weerd) to make a blue marked area on image located in picture box. Whats my problem now is to process this area afterwards. I need that when I release left mouse button, this rectangle dissapears again. Right now, it persist even when I put new image into picture box. Only way to dispose this rectangle is to click right mouse button at the end, but I need to make it work even when just left mouse button is released.

private Point RectStartPoint;
private Rectangle Rect = new Rectangle();
private Brush selectionBrush = new SolidBrush(Color.FromArgb(128, 72, 145, 220));

// Start Rectangle
//
private void pictureBox1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
    // Determine the initial rectangle coordinates...
    RectStartPoint = e.Location;
    Invalidate();
}

// Draw Rectangle
//
private void pictureBox1_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
{
    if (e.Button != MouseButtons.Left)
        return;
    Point tempEndPoint = e.Location;
    Rect.Location = new Point(
        Math.Min(RectStartPoint.X, tempEndPoint.X),
        Math.Min(RectStartPoint.Y, tempEndPoint.Y));
    Rect.Size = new Size(
        Math.Abs(RectStartPoint.X - tempEndPoint.X),
        Math.Abs(RectStartPoint.Y - tempEndPoint.Y));
    pictureBox1.Invalidate();
}

// Draw Area
//
private void pictureBox1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
    // Draw the rectangle...
    if (pictureBox1.Image != null)
    {
        if (Rect != null && Rect.Width > 0 && Rect.Height > 0)
        {
            e.Graphics.FillRectangle(selectionBrush, Rect);
        }
    }
}

private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Right)
    {
        if (Rect.Contains(e.Location))
        {
            Debug.WriteLine("Right click");
        }
    }
}
  • Use a flag to decide whether to paint or not! You can set it in the mdown and reset in the mUp event. In the mUp also put an Invalidate. (The one in themDown seems unnecessary, imo) – TaW May 12 '18 at 08:36
  • 1
    Incredible, thank you. I was aiming this way so I had it all set, the bit I was missing was to test selection flag in Paint method (for some reason I tested it only in mDown and mUp methods, 1 condition added and it all worked. Thank you very much! – Petr Klíč May 12 '18 at 13:01

0 Answers0