0

任务:我有两台显示器。我需要在#1 上展示#2 发生了什么。换句话说,第一台显示器只不过是第二台的反射器。

当前解决方案:每隔约 100 毫秒制作一次屏幕截图并重新渲染。以下方法负责捕获屏幕截图:

private BitmapSource MakeScreenshot(Screen screen)
    {
        using (var screenBmp = new Bitmap(screen.Bounds.Width, screen.Bounds.Height, PixelFormat.Format32bppArgb))
        {
            using (var bmpGraphics = Graphics.FromImage(screenBmp))
            {
                bmpGraphics.CopyFromScreen(screen.Bounds.X, screen.Bounds.Y, 0, 0, screen.Bounds.Size);

                return 
                    Imaging.CreateBitmapSourceFromHBitmap(
                        screenBmp.GetHbitmap(),
                        IntPtr.Zero,
                        Int32Rect.Empty,
                        BitmapSizeOptions.FromEmptyOptions());
            }
        }
    }

之后,我使用 Start(...) 方法将我的“反射”从第二个屏幕运行到第一个屏幕:

public void Start(int delay, int period)
    {
        if (_timer != null) throw new InvalidOperationException();

        _timer = new System.Threading.Timer(
            _ =>
            {
                _placeholder
                    .Dispatcher
                    .Invoke(() =>
                    {
                        _placeholder.Source = MakeScreenshot(_targetScreen); // re-render new screenshot
                    });
            }, 
            null, 
            delay, 
            period);
    }

问题:经过大约 30-40 秒的相当不错的运行后,它会因 OutOfMemoryException 而失败。我在这里调查了一些帖子,但没有发现任何关于我的问题。

4

1 回答 1

3

那是因为你在这里泄漏内存:

Imaging.CreateBitmapSourceFromHBitmap(
    screenBmp.GetHbitmap(), // < here
    IntPtr.Zero,
    Int32Rect.Empty,
    BitmapSizeOptions.FromEmptyOptions());

调用后需要释放 GDI 位图使用的内存screenBmp.GetHbitmap()。像这样改变:

private BitmapSource MakeScreenshot(Screen screen)
{
    using (var screenBmp = new Bitmap(screen.Bounds.Width, screen.Bounds.Height, PixelFormat.Format32bppArgb))
    {
        using (var bmpGraphics = Graphics.FromImage(screenBmp))
        {
            bmpGraphics.CopyFromScreen(screen.Bounds.X, screen.Bounds.Y, 0, 0, screen.Bounds.Size);
            var handle = screenBmp.GetHbitmap();
            try {
                return
                    Imaging.CreateBitmapSourceFromHBitmap(
                        handle,
                        IntPtr.Zero,
                        Int32Rect.Empty,
                        BitmapSizeOptions.FromEmptyOptions());
            }
            finally {
                DeleteObject(handle);
            }
        }
    }
}

[System.Runtime.InteropServices.DllImport("gdi32.dll")]
public static extern bool DeleteObject(IntPtr hObject);

它不应该再泄漏了。

于 2017-03-16T09:34:11.717 回答