JOE
JOE

Reputation: 373

How to detect when the image appears in PictureBox

I have a problem about System.Windows.Forms.PictureBox. I want to show a image on monitor and capture it on the camera. So I use Winform which include a picturebox. The picture box is:

PictureBox pb = new PictureBox();
pb.WaitOnLoad = true;

When I set a bitmap to PictureBox and capture the image from camera,

// Show bmp1
this.image.Image = bmp1;
this.image.Invalidate();
this.image.Refresh();

// Delay 1s
UseTimerToDelay1s();

// Show bmp2
this.image.Image = bmp2;
this.image.Invalidate();
this.image.Refresh();

// Capture
CaptureImageFromCamera();

It only capture the bmp1.

If I add a small delay like this,

this.image.Image = bmp2;
this.image.Invalidate();
this.image.Refresh();
UseTimerToDelay100ms();
CaptureImageFromCamera();

It capture bmp2. The Image set method seem to be a async method. Does any method to confirm the image is set? Thanks.

Upvotes: 2

Views: 1083

Answers (1)

Reza Aghaei
Reza Aghaei

Reputation: 125197

I'd use the first Paint event after assigning the new Image. You can give it a try using a very large image url from this site.

The example uses google logo image url. Copy the following code and make sure you assign event handlers to the events:

bool newImageInstalled = true;
private void Form1_Load(object sender, EventArgs e)
{
    pictureBox1.WaitOnLoad = true;
}
private void PictureBox1_Paint(object sender, PaintEventArgs e)
{
    if (!newImageInstalled)
    {
        newImageInstalled = true;
        BeginInvoke(new Action(() =>
        {
            //Capturing the new image
            using (var bm = new Bitmap(pictureBox1.ClientSize.Width, 
                pictureBox1.ClientSize.Height))
            {
                pictureBox1.DrawToBitmap(bm, pictureBox1.ClientRectangle);
                var tempFile = System.IO.Path.GetTempFileName() + ".png";
                bm.Save(tempFile, System.Drawing.Imaging.ImageFormat.Png);
                System.Diagnostics.Process.Start(tempFile);
            }
        }));
    }
}
private void button1_Click(object sender, EventArgs e)
{
    newImageInstalled = false;
    pictureBox1.ImageLocation = 
    "https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png";
}
private void button2_Click(object sender, EventArgs e)
{
    newImageInstalled = false;
    pictureBox1.Image = null;
}

Upvotes: 2

Related Questions