PictureBox资源发布

PictureBox resources release

我想制作一个屏幕缩放器,它可以捕获屏幕的一部分并将其缩放。下面的代码现在可以捕获屏幕并在 PictureBox 中播放。但是我有这个问题,当我打开程序时,我的内存不断增长。我想一定是有些资源没有释放,不知道怎么释放。

我把它做成了一个媒体播放器,但不是播放视频,而是播放当前屏幕的一部分。

public partial class Form1 : Form
{

    PictureBox picBox;
    Bitmap bit;
    Graphics g;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        picBox = pictureBox;
    }

    private void CopyScreen()
    {

        bit = new Bitmap(this.Width, this.Height);
        g = Graphics.FromImage(bit as Image);

        Point upperLeftSource = new Point(
            Screen.PrimaryScreen.Bounds.Width / 2 - this.Width / 2,
            Screen.PrimaryScreen.Bounds.Height / 2 - this.Height / 2);

        g.CopyFromScreen(upperLeftSource, new Point(0, 0), bit.Size);

        picBox.Image = Image.FromHbitmap(bit.GetHbitmap());

        bit.Dispose();
        g.Dispose();
    }

    private void timer_Tick(object sender, EventArgs e)
    {
        CopyScreen();
    }

问题在于您对 GetHbitmap 的使用,以及当您将新的 Image 分配给 [=15] 时您没有处理之前的 Image =].

https://msdn.microsoft.com/en-us/library/1dz311e4(v=vs.110).aspx 状态:

You are responsible for calling the GDI DeleteObject method to free the memory used by the GDI bitmap object.

(你没有做)

考虑更改代码以避免需要 GetHbitmap 调用(以及 Dispose 之前的 Image):

private void CopyScreen()
{
    bit = new Bitmap(this.Width, this.Height);
    g = Graphics.FromImage(bit);

    Point upperLeftSource = new Point(
        Screen.PrimaryScreen.Bounds.Width / 2 - this.Width / 2,
        Screen.PrimaryScreen.Bounds.Height / 2 - this.Height / 2);

    g.CopyFromScreen(upperLeftSource, new Point(0, 0), bit.Size);

    var oldImage = picBox.Image;
    picBox.Image = bit;
    oldImage?.Dispose();

    g.Dispose();
}

为了进一步简化它,删除您在 class 顶部声明的字段,然后只使用:

private void CopyScreen()
{
    var picBox = pictureBox;
    var bit = new Bitmap(this.Width, this.Height);

    using (var g = Graphics.FromImage(bit))
    {
        var upperLeftSource = new Point(
            Screen.PrimaryScreen.Bounds.Width / 2 - this.Width / 2,
            Screen.PrimaryScreen.Bounds.Height / 2 - this.Height / 2);

        g.CopyFromScreen(upperLeftSource, new Point(0, 0), bit.Size);

        var oldImage = picBox.Image;
        picBox.Image = bit;
        oldImage?.Dispose();
    }
}