Davin Timothy Ivander
Davin Timothy Ivander

Reputation: 45

C# apps using ram and cannot be cleared

Okay, i had create an apps and the apps are eating ram too much.

The Problem:

How the program works

How the "space" works:

PictureBox frame = new PictureBox();
frame.Size = target.Size;
frame.SizeMode = PictureBoxSizeMode.CenterImage;
frame.Image = get_img();
frame.Location = new Point(mouse.X - (target.Width / 2), mouse.Y - (target.Height / 2));
this.Controls.Add(frame);
frame.BringToFront();
box.Add(frame);
go_transparant();

How the "1" works:

foreach(var i in box){
   this.Controls.Remove(i);
   i.Dispose();
}
box.Clear();
box = new List<PictureBox>();

get_img function:

this.Visible = false;
using (Bitmap ss = new Bitmap(sc.CaptureScreen()))
{
    this.Visible = true;

    result = ss.Clone(new Rectangle(mouse.X - target.Width / 2, mouse.Y - target.Height / 2, target.Width, target.Height),
    ss.PixelFormat);

    return result;
}

go_transparant function:

int wl = GetWindowLong(this.Handle, GWL.ExStyle);
wl = wl | 0x80000 | 0x20;
SetWindowLong(this.Handle, GWL.ExStyle, wl);
SetLayeredWindowAttributes(this.Handle, 0, 150, LWA.Alpha);
this.AllowTransparency = true;
this.TransparencyKey = Color.Violet;
this.BackColor = Color.Violet;

FULL CODE:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using Gma.UserActivityMonitor;

namespace LoA_Tarrot_Helper
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        public enum GWL
        {
            ExStyle = -20
        }

        public enum WS_EX
        {
            Transparent = 0x20,
            Layered = 0x80000
        }

        public enum LWA
        {
            ColorKey = 0x1,
            Alpha = 0x2
        }

        [DllImport("user32.dll", EntryPoint = "GetWindowLong")]
        public static extern int GetWindowLong(IntPtr hWnd, GWL nIndex);

        [DllImport("user32.dll", EntryPoint = "SetWindowLong")]
        public static extern int SetWindowLong(IntPtr hWnd, GWL nIndex, int dwNewLong);

        [DllImport("user32.dll", EntryPoint = "SetLayeredWindowAttributes")]
        public static extern bool SetLayeredWindowAttributes(IntPtr hWnd, int crKey, byte alpha, LWA dwFlags);

        [DllImport("user32.dll", EntryPoint = "GetCursorPos")]
        public static extern bool GetCursorPos(ref Point lpPoint);

        private void go_transparant()
        {
            int wl = GetWindowLong(this.Handle, GWL.ExStyle);
            wl = wl | 0x80000 | 0x20;
            SetWindowLong(this.Handle, GWL.ExStyle, wl);
            SetLayeredWindowAttributes(this.Handle, 0, 150, LWA.Alpha);
            this.AllowTransparency = true;
            this.TransparencyKey = Color.Violet;
            this.BackColor = Color.Violet;
        }
        private void prepare() 
        {
            target.Multiline = true;
            target.Enabled = false;
            target.Size = new Size(80, 80);
            target.BackColor = Color.Violet;
            this.Controls.Add(target);

            this.WindowState = FormWindowState.Maximized;
            this.TopMost = true;
        }
        TextBox target = new TextBox();
        List<PictureBox> box = new List<PictureBox>();

        private void Form1_Load(object sender, EventArgs e)
        {
            prepare();
            go_transparant();
            timer1.Start();
            HookManager.KeyUp += HookManager_KeyUp;
        }
        ScreenCapture sc = new ScreenCapture();
        Bitmap result;
        private Bitmap get_img() 
        {
            this.Visible = false;
            using (Bitmap ss = new Bitmap(sc.CaptureScreen()))
            {
                this.Visible = true;
                //Graphics g3 = Graphics.FromImage(bmp);
                //g3.DrawImageUnscaled(ss, mouse.X-target.Width/2, mouse.Y-target.Height/2, target.Width, target.Height);

                /*Rectangle cropRect = new Rectangle(,);
                Bitmap src = Image.FromFile(fileName) as Bitmap;
                Bitmap target = new Bitmap(cropRect.Width, cropRect.Height);
                using (Graphics g = Graphics.FromImage(target))
                {
                    g.DrawImage(src, new Rectangle(0, 0, target.Width, target.Height),
                                     cropRect,
                                     GraphicsUnit.Pixel);
                }

                Graphics g2 = frame.CreateGraphics();
                g2.DrawImageUnscaled(bmp, 0, 0, target.Width, target.Height);*/


                result = ss.Clone(new Rectangle(mouse.X - target.Width / 2, mouse.Y - target.Height / 2, target.Width, target.Height),
                ss.PixelFormat);

                /*pictureBox1.Image = ss;
                pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;

                pictureBox2.Image = result;
                pictureBox2.SizeMode = PictureBoxSizeMode.Zoom;*/
                //ss.Dispose();
                return result;
            }
        }

        void HookManager_KeyUp(object sender, KeyEventArgs e)
        {
            try { 
                if (e.KeyCode == Keys.Space)
                {
                    PictureBox frame = new PictureBox();
                    frame.Size = target.Size;
                    frame.SizeMode = PictureBoxSizeMode.CenterImage;
                    frame.Image = get_img();
                    frame.Location = new Point(mouse.X - (target.Width / 2), mouse.Y - (target.Height / 2));
                    this.Controls.Add(frame);
                    frame.BringToFront();
                    box.Add(frame);
                    go_transparant();

                }
                if (e.KeyCode == Keys.D1) {
                    foreach(var i in box){
                        this.Controls.Remove(i);
                        i.Dispose();
                    }
                    box.Clear();
                    box = new List<PictureBox>();
                }
            }
            catch (Exception ex) { MessageBox.Show("ERROR: " + ex.Message);}
        }
        Point mouse = new Point();
        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                GetCursorPos(ref mouse);
                if (target != null)
                {
                    target.Location = new Point(mouse.X - target.Width / 2, mouse.Y - target.Height / 2);
                }
            }
            catch (Exception ex) { MessageBox.Show("ERROR: " + ex.Message); timer1.Stop(); timer1.Start(); }
        }

    }
}

Upvotes: 0

Views: 218

Answers (2)

Compa
Compa

Reputation: 190

Check this thread How does C# manage memory allocated by a new operator inside a loop?

My guess is that the memory is reserved and managed by the OS and/or the garbage collector and deppending on the usage of the app, it might stay "reserved" or be released.

We developed a program here that reads hundreds XML and connects to SAP Business One creating hundreds of transactions per day. We close connections and dispose objects as often as we can but the behaviour is always the same: The program starts at 1mb of ram but as soon as the proccess starts, it goes up to 1gb and never goes down.

The proccess occurs once every 24 hours at least (sometimes they force the proccess to start earlier and perform it 2 or 3 times in the same day) and the program uses the already reserved memory, it does not consume more.

Upvotes: 0

Martin
Martin

Reputation: 16433

Even though you are disposing of the objects, the memory will only actually be released when the Garbage Collector runs. You can force this to happen explicitly by running the following code:

GC.Collect();
GC.WaitForPendingFinalizers();

However, it's not recommended to do this yourself as the Garbage Collector is intended to run when it is optimal.

Why do you need to explicitly reduce the memory used by your application when you have disposed your objects?

Upvotes: 1

Related Questions