Oskar Marciniak
Oskar Marciniak

Reputation: 13

selected area to cut an image

Hi I would do the selected area to cut an image on picturebox control.

I have the following code:

using System;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{

public partial class Form1 : Form
{
    private Rectangle rect;
    private Pen p;

    public Form1()
    {
        InitializeComponent();
    }

    private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        if (this.p == null)
            this.p = new Pen(Color.FromArgb(100, 200, 200, 200), 5);
        if (this.rect.Width > 0)
            e.Graphics.DrawRectangle(this.p, this.rect);
    }

    private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    {

        if (e.X < this.rect.X)
        {
            this.rect.Width = this.rect.X - e.X;
            this.rect.X = e.X;
        }
        else
        {
            this.rect.Width = e.X - this.rect.X;
        }

        if (e.Y < this.rect.Y)
        {
            this.rect.Height = this.rect.Y - e.Y;
            this.rect.Y = e.Y;
        }
        else
        {
            this.rect.Height = e.Y - this.rect.Y;
        }

        this.Invalidate(this.rect);

    }

    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        this.rect.X = e.X;
        this.rect.Y = e.Y;
    }

}

}

It returns an error here:

Application.Run(new Form1());

Why?

thanks for all replies ;p

Upvotes: 1

Views: 2481

Answers (3)

Shadow Wizard
Shadow Wizard

Reputation: 66389

Try using this optimized code, if you still get error post it here (edit your original question) and we'll see.

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
   if (this.p == nulll)
      this.p = new Pen(Color.FromArgb(100, 200, 200, 200), 5);
   if (this.rect.Width > 0)
      e.Graphics.DrawRectangle(this.p, this.rect);
}

Upvotes: 1

John Koerner
John Koerner

Reputation: 38077

You shouldn't dispose of the Graphics object that is passed as part of the PaintEventArgs. That is probably what is causing your issue.

Upvotes: 3

Adam Straughan
Adam Straughan

Reputation: 2848

what is the error?

you are leaking Pen's. For every paint message you create a new pen and throw the old without disposing.

Off the top of my head I can't remember if you should dispose of the graphics object you get from the event args

Upvotes: 0

Related Questions