private void SetBox(string result) { //InvokeRequired属性需要比较调用线程和创建线程的线程ID,如果俩线程ID不同,则返回true if (searchFace.InvokeRequired)//调用和创建该控件的线程是不同的线程,必须调用Invoke方法 { if (!closing) { //创建该方法的委托实例 SetBitmapCallback d = new SetBitmapCallback(SetBox); //调用该委托实例,并传递参数,参数为object类型,使用this调用Invoke(this为当前窗体,是创建该窗体控件的线程) Invoke(d, new object[] { result });//this指定创建该控件的线程来Invoke(调用) } } else//调用与创建该控件的线程是同一个线程 { if (closing) { return; } if (result != "0") { if (searchFace.BackgroundImage != null) { searchFace.BackgroundImage.Dispose(); searchFace.BackgroundImage = null; } if (faceBox.BackgroundImage != null) { faceBox.BackgroundImage.Dispose(); faceBox.BackgroundImage = null; } } switch (result) { case "0": result = "检测到人脸!"; break; case "-1": result = "没有找到人脸检测模型!"; break; case "-2": result = "图像读取失败!"; break; case "-3": result = "检测程序运行失败!"; break; case "-4": result = "绘制图像失败!"; break; case "-5": result = "保存图像失败!"; break; case "-6": result = "没有检测到人脸!"; break; } label2.Text = result; } }
public void CreateBitmap(Image img) { if (pictureBox1.InvokeRequired)//调用和创建该控件的线程是不同的线程,必须调用Invoke方法 { if (close) { return; } //创建该方法的委托实例 SetBitmapCallback d = new SetBitmapCallback(CreateBitmap); //调用该委托实例,并传递参数,参数为object类型,使用this调用Invoke(this为当前窗体,是创建该窗体控件的线程) Invoke(d, new object[] { img });//this指定创建该控件的线程来Invoke(调用) } else//调用与创建该控件的线程是同一个线程 { if (img != null) { Bitmap bitmap = new Bitmap(img); if (process) { BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb); int success = FaceApi.DrawFaces(bitmapData.Scan0, bitmapData.Width, bitmapData.Height, bitmapData.Stride, 3); bitmap.UnlockBits(bitmapData); if (pictureBox1.BackgroundImage != null) { pictureBox1.BackgroundImage.Dispose(); pictureBox1.BackgroundImage = null; } pictureBox1.BackgroundImage = bitmap; } else { if (pictureBox1.BackgroundImage != null) { pictureBox1.BackgroundImage.Dispose(); pictureBox1.BackgroundImage = null; } pictureBox1.BackgroundImage = bitmap; } } else { if (pictureBox1.BackgroundImage != null) { pictureBox1.BackgroundImage.Dispose(); pictureBox1.BackgroundImage = null; } } } }