3

因此,我的 C# 代码存在一些内存泄漏问题,我已经进行了相当彻底的搜索,并且确实意识到这里还有另一个问题WPF CreateBitmapSourceFromHBitmap() 内存泄漏(以及许多其他问题)涵盖了相同的主题但不满足我的标准或解决我的问题。

所以这是我的代码,不久前我从另一个项目中得到了这个我相当肯定这个问题与// Here's the WPF glue to make it all work. It converts from an // hBitmap to a BitmapSource. Love the WPF interop functions bitmap = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( compatibleBitmapHandle, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());

这是完整的方法代码,它是这样调用的

BitmapSource captured = CaptureRegion( hWnd, rect.X, rect.Y, rect.Width, rect.Height, true);

并且每秒也被调用多次。(每次调用 70-100 毫秒)

      // capture a region of a the screen, defined by the hWnd
        public static BitmapSource CaptureRegion(
            IntPtr hWnd, int x, int y, int width, int height, bool addToClipboard)
        {
            IntPtr sourceDC = IntPtr.Zero;
            IntPtr targetDC = IntPtr.Zero;
            IntPtr compatibleBitmapHandle = IntPtr.Zero;
            BitmapSource bitmap = null;
            //IntPtr hBitmap = bitmap.GetHbitmap();
//            IntPtr hBitmap;

            try
            {
                // gets the main desktop and all open windows
                sourceDC = User32.GetDC(User32.GetDesktopWindow());

                //sourceDC = User32.GetDC(hWnd);
                targetDC = Gdi32.CreateCompatibleDC(sourceDC);

                // create a bitmap compatible with our target DC
                compatibleBitmapHandle = Gdi32.CreateCompatibleBitmap(sourceDC, width, height);

                // gets the bitmap into the target device context
                Gdi32.SelectObject(targetDC, compatibleBitmapHandle);

                // copy from source to destination
                Gdi32.BitBlt(targetDC, 0, 0, width, height, sourceDC, x, y, Gdi32.SRCCOPY);

                // Here's the WPF glue to make it all work. It converts from an 
                // hBitmap to a BitmapSource. Love the WPF interop functions
                bitmap = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                    compatibleBitmapHandle, IntPtr.Zero, Int32Rect.Empty,
                    BitmapSizeOptions.FromEmptyOptions());

            }
            catch (Exception ex)
            {
                throw new ScreenCaptureException(string.Format("Error capturing region {0},{1},{2},{3}", x, y, width, height), ex);
            }
            finally
            {
                Gdi32.DeleteObject(compatibleBitmapHandle);
                // Gdi32.DeleteObject(hBitmap);
                User32.ReleaseDC(IntPtr.Zero, sourceDC);
                User32.ReleaseDC(IntPtr.Zero, targetDC);
            }

            return bitmap;
        }

我真的无法理解如何将上述线程中提到的修复程序应用于我的问题,因为我的 BitmapSource 似乎不是从位图创建的,我看不出删除位图对象有什么帮助。

非常感谢你的帮助。

4

0 回答 0