c# Bitmap is already locked 截图

c# Bitmap is already locked screenshots

我正在尝试制作一个程序来截取屏幕截图并进行比较。

这是代码示例

比较方法:

    [DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl)]
    static extern int memcmp(IntPtr b1, IntPtr b2, UIntPtr count);


  public bool CompareMemCmp(Bitmap b1, Bitmap b2)
    {

        if ((b1 == null) != (b2== null)) return false;
        //  if (b1.Size != b2.Size) return false;



             var bd1 = b1.LockBits(new Rectangle(new Point(0, 0), b1.Size), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
        var bd2 = b2.LockBits(new Rectangle(new Point(0, 0), b2.Size), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);


            IntPtr bd1scan0 = bd1.Scan0;
            IntPtr bd2scan0 = bd2.Scan0;

            int stride = bd1.Stride;
            int len = stride * b1.Height;

            return memcmp(bd1scan0, bd2scan0, (UIntPtr)(len)) == 0;


    }

这是主要代码:

 private void MainForm_Load(object sender, EventArgs e)
    {


        prev = CaptureScreen.GetDesktopImage();
        th = new Thread(new ThreadStart(capture));
        th.Start();
    }

      private void capture()
    {


        while (true)
        {

            current = CaptureScreen.GetDesktopImage();

            if (CompareMemCmp(prev, current))
            {
              label1.Invoke(new Action(() => label1.Text="changed"));
                prev = current;
            }

            else
                label1.Invoke(new Action(() => label1.Text = "same"));

            count++;

        }


    }

我在该行的 CompareMemCmp 方法中遇到了一个奇怪的错误

 var bd1 = b1.LockBits(new Rectangle(new Point(0, 0), b1.Size), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);

我想这与截屏有关。因为当我只比较一个目录中的 2 张图像时它工作正常...知道如何释放它们吗?

完成比较后,您应该在位图上调用 UnlockBits()。请参阅 MSDN.

上的示例
...
int stride = bd1.Stride;
int len = stride * b1.Height;

b1.UnlockBits(bd1);
b2.UnlockBits(bd2);

return memcmp(bd1scan0, bd2scan0, (UIntPtr)(len)) == 0;
...