如何检测图像何时出现在 PictureBox 中

How to detect when the image appears in PictureBox

我有一个关于 System.Windows.Forms.PictureBox 的问题。我想在显示器上显示图像并在相机上捕捉它。所以我使用包含图片框的 Winform。图片框为:

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

当我将位图设置为 PictureBox 并从相机捕获图像时,

// 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();

它只捕获 bmp1。

如果我像这样添加一个小延迟,

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

它捕获bmp2。图像设置方法似乎是一种异步方法。是否有任何方法来确认图像已设置?谢谢

我会在分配新的 Image 后使用第一个 Paint 事件。 您可以尝试使用非常大的 image url from this site.

该示例使用 google 徽标图像 url。复制以下代码并确保将事件处理程序分配给事件:

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;
}