Flaviola
Flaviola

Reputation: 63

Color Dialog box not showing up

I have a small app that looks pretty much like old Paint from Windows. I implemented all the Graphic using picture box Paint event. The only problem is that when I click this button a Color Dialog box should appear and let me change the color of my pen. But whenever I click the button the box never appears and my program gets stuck in the Paint event, most precisely at the line where I do the following:

pictureBox1.Image = bmp; 

What I am doing wrong? Please, I would appreciate any help!

I hope the following code snippet is enough.

This is my picturebox Paint event:

private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        using(Graphics g = Graphics.FromImage(bmp))
        {
            if (lineButton && mouseIsUp)
            {
                g.DrawLine(myPen, mAnchorPoint, mFinalPoint);
                mAnchorPoint = Point.Empty;
                mFinalPoint = Point.Empty;

            }
            pictureBox1.Image = bmp;
        }
    }

And this is the button event that fires up when I wish to change my pen color:

private void ColorButton_Click(object sender, EventArgs e)
    {
                ColorDialog cd = new ColorDialog();
                if (cd.ShowDialog() == DialogResult.OK)
                {
                    myPen.Color = cd.Color;
                }

    }

Upvotes: 2

Views: 952

Answers (1)

Don't use pictureBox1.Image = bmp; inside pictureBox1_Paint. Instead:

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    using(Graphics g = Graphics.FromImage(bmp))
    {
        if (lineButton && mouseIsUp)
        {
            g.DrawLine(myPen, mAnchorPoint, mFinalPoint);
            mAnchorPoint = Point.Empty;
            mFinalPoint = Point.Empty;

        }
        //pictureBox1.Image = bmp;
    }

    e.Graphics.DrawImage(bmp, 0, 0);
}

Or, a better approach, set pictureBox1.Image = bmp; once, do all your drawings on bmp(not in pictureBox1_Paint) and final call pictureBox1.Invalidate();. You don't need to write code in pictureBox1_Paint().

Upvotes: 3

Related Questions