Hello,
I created an application to track currently Active Window on the screen. I am using Timer and subscribing its Elapsed event so it can process my code. I have set the timer Interval to 2 seconds.
As I run this application I see increase value of Private Bytes (reflecting in TaskManager) and it keeps on increasing.
After watching youtube videos I tried to set all possible objects to Null for proper disposal and also set used "Using" statement to reclaim memory from native objects.
class myservice
{
public void Start()
{
Timer tActiveWin = new Timer();
tActiveWin.Interval = TimeSpan.FromSeconds(2).TotalMilliseconds;
tActiveWin.Elapsed += TActiveWin_Elapsed;
tActiveWin.AutoReset = true;
tActiveWin.Enabled = true;
}
private void TActiveWin_Elapsed(object sender, ElapsedEventArgs e)
{
var win = new WindowEvents().GetActiveWindow();
Console.WriteLine(win.activewindowtitle);
}
}
class WindowEvents
{
[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
[DllImport("user32.dll", SetLastError = true)]
static extern int GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);
public JsonAppEvents.Activewindow GetActiveWindow()
{
Task<JsonAppEvents.Activewindow> activeWindow = Task.Factory.StartNew(() =>
{
JsonAppEvents.Activewindow activeWin = new JsonAppEvents.Activewindow();
IntPtr hWnd = GetForegroundWindow();
int processID = 0;
int threadID = GetWindowThreadProcessId(hWnd, out processID);
using (Process p = Process.GetProcessById(processID))
{
StringBuilder text = new StringBuilder(256);
if (GetWindowText(hWnd, text, 256) > 0)
{
text.ToString();
}
activeWin.activewindowfullpath = p.MainModule.FileName;
activeWin.activewindowtitle = p.MainWindowTitle;
activeWin.time = p.StartTime.ToString("ddd, dd MMM yyyy HH:mm:ss");
activeWin.activewindowdescription = p.MainModule.ModuleName;
p.Dispose();
hWnd = IntPtr.Zero;
processID = 0;
threadID = 0;
text.Clear();
text = null;
return activeWin;
}
});
return activeWindow.Result;
}
}
class JsonAppEvents
{
public class Activewindow
{
public string activewindowfullpath { get; set; }
public string activewindowdescription { get; set; }
public string time { get; set; }
public string activewindowtitle { get; set; }
}
}
After running the program I captured Private bytes as follows :
PrivateBytes Time
-----------------------
5,300 K 8:45 PM
5,800 K 8:46 PM
7,252 K 8:47 PM
7,260 K 8:49 PM
------------------------------
I am looking for some help on it so i can stabilise Private Bytes from getting increase and can trace it properly why is it happening? is there something wrong with my code?
What I have tried:
- Searching on internet object disposal
- I tried to set all possible objects to Null for proper disposal and also set used.