【问题标题】:PictureBox resources releasePictureBox 资源发布
【发布时间】:2017-10-27 09:47:40
【问题描述】:

我想制作一个屏幕缩放器,它可以捕捉屏幕的一部分并进行缩放。下面的代码现在可以捕获屏幕并在 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();
    }

【问题讨论】:

  • @mjwills 它确实有效......内存仍在不断增长
  • @mjwills 我将计时器的间隔设置为 20,因此内存增长非常快,例如每秒 10MB

标签: c# picturebox


【解决方案1】:

问题在于您对GetHbitmap 的使用,以及当您将新的Image 分配给PictureBox 时,您并没有处理以前的Image。

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

你负责调用 GDI DeleteObject 方法来释放 GDI 位图对象使用的内存。

(你没有这样做)

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

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();
}

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

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();
    }
}

【讨论】:

  • 非常感谢您抽出宝贵时间帮助我!您和所有贡献自己的人使 Stack Overflow 成为程序员提问的最佳场所!我很佩服你,我会尽我所能帮助别人。对不起我的英语不好。
猜你喜欢
  • 1970-01-01
  • 2011-01-17
  • 1970-01-01
  • 1970-01-01
  • 2023-03-06
  • 1970-01-01
  • 1970-01-01
  • 2011-06-10
  • 1970-01-01
相关资源
最近更新 更多