forked from zeh/app-application-logger
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MainForm.cs
592 lines (477 loc) · 17.3 KB
/
MainForm.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
using ApplicationLogger.Properties;
using System;
using Microsoft.Win32;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
namespace ApplicationLogger
{
public partial class MainForm : Form
{
// Constants
private const string SETTINGS_FIELD_RUN_AT_STARTUP = "RunAtStartup";
private const string REGISTRY_KEY_ID = "ApplicationLogger"; // Registry app key for when it's running at startup
// Properties
private Timer timerCheck;
private ContextMenu contextMenu;
private MenuItem menuItemOpen;
private MenuItem menuItemOpenLog;
private MenuItem menuItemStartStop;
private MenuItem menuItemRunAtStartup;
private MenuItem menuItemExit;
private bool allowClose;
private bool allowShow;
private bool isRunning;
private bool isUserIdle;
private bool hasInitialized;
private int numberOfTCPAttempts = 0;
private ConfigManager configMgr = new ConfigManager();
private LoggingManager logMgr;
private PowerChecker powerChecker;
//Variables for ICP
TcpClient tcpclient;
Stream stm;
ASCIIEncoding asen = new ASCIIEncoding();
bool isConnectedIPCServer = false;
int IPCSkipCount = 0;
delegate void SetTextCallback(string text);
public MainForm()
{
InitializeComponent();
initializeForm();
}
private void onFormLoad(object sender, EventArgs e)
{
// First time the form is shown
}
protected override void SetVisibleCore(bool isVisible)
{
if (!allowShow)
{
// Initialization form show, when it's ran: doesn't allow showing form
isVisible = false;
if (!this.IsHandleCreated) CreateHandle();
}
base.SetVisibleCore(isVisible);
}
private void onFormClosing(object sender, FormClosingEventArgs e)
{
// Form is attempting to close
if (!allowClose)
{
// User initiated, just minimize instead
e.Cancel = true;
Hide();
}
}
private void onFormClosed(object sender, FormClosedEventArgs e)
{
// Stops everything
stop();
// If debugging, un-hook itself from startup
if (System.Diagnostics.Debugger.IsAttached && windowsRunAtStartup) windowsRunAtStartup = false;
}
private void onResize(object sender, EventArgs e)
{
// Resized window
//notifyIcon.BalloonTipTitle = "Minimize to Tray App";
//notifyIcon.BalloonTipText = "You have successfully minimized your form.";
if (WindowState == FormWindowState.Minimized)
{
//notifyIcon.ShowBalloonTip(500);
this.Hide();
}
}
private void onMenuItemOpenClicked(object Sender, EventArgs e)
{
showForm();
}
private void onMenuItemStartStopClicked(object Sender, EventArgs e)
{
if (isRunning)
{
stop();
}
else
{
start();
}
}
private void onMenuItemOpenLogClicked(object Sender, EventArgs e)
{
logMgr.commitLines();
Process.Start(logMgr.getLogFileName());
}
private void onMenuItemRunAtStartupClicked(object Sender, EventArgs e)
{
menuItemRunAtStartup.Checked = !menuItemRunAtStartup.Checked;
settingsRunAtStartup = menuItemRunAtStartup.Checked;
applySettingsRunAtStartup();
}
private void onMenuItemExitClicked(object Sender, EventArgs e)
{
exit();
}
private void onDoubleClickNotificationIcon(object sender, MouseEventArgs e)
{
showForm();
}
private bool windowsRunAtStartup
{
// Whether it's actually set to run at startup or not
get
{
return getStartupRegistryKey().GetValue(REGISTRY_KEY_ID) != null;
}
set
{
if (value)
{
// Add
getStartupRegistryKey(true).SetValue(REGISTRY_KEY_ID, Application.ExecutablePath.ToString());
//Console.WriteLine("RUN AT STARTUP SET AS => TRUE");
}
else
{
// Remove
getStartupRegistryKey(true).DeleteValue(REGISTRY_KEY_ID, false);
//Console.WriteLine("RUN AT STARTUP SET AS => FALSE");
}
}
}
private RegistryKey getStartupRegistryKey(bool writable = false)
{
return Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", writable);
}
public void updateContextMenu()
{
// Update start/stop command
if (menuItemStartStop != null)
{
if (isRunning)
{
menuItemStartStop.Text = "&Stop";
}
else
{
menuItemStartStop.Text = "&Start";
}
}
// Update filename
if (menuItemOpenLog != null)
{
var filename = logMgr.getLogFileName();
if (!System.IO.File.Exists(filename))
{
// Doesn't exist
menuItemOpenLog.Text = "Open &log file";
menuItemOpenLog.Enabled = false;
}
else
{
// Exists
menuItemOpenLog.Text = "Open &log file (" + filename + ")";
menuItemOpenLog.Enabled = true;
}
}
}
private void updateTrayIcon()
{
if (isRunning)
{
notifyIcon.Icon = ApplicationLogger.Properties.Resources.iconNormal;
notifyIcon.Text = "Application Logger (started)";
}
else
{
notifyIcon.Icon = ApplicationLogger.Properties.Resources.iconStopped;
notifyIcon.Text = "Application Logger (stopped)";
}
}
private void createContextMenu()
{
// Initialize context menu
contextMenu = new ContextMenu();
// Initialize menu items
menuItemOpen = new MenuItem();
menuItemOpen.Index = 0;
menuItemOpen.Text = "&Open";
menuItemOpen.Click += new EventHandler(onMenuItemOpenClicked);
contextMenu.MenuItems.Add(menuItemOpen);
menuItemStartStop = new MenuItem();
menuItemStartStop.Index = 0;
menuItemStartStop.Text = ""; // Set later
menuItemStartStop.Click += new EventHandler(onMenuItemStartStopClicked);
contextMenu.MenuItems.Add(menuItemStartStop);
contextMenu.MenuItems.Add("-");
menuItemOpenLog = new MenuItem();
menuItemOpenLog.Index = 0;
menuItemOpenLog.Text = ""; // Set later
menuItemOpenLog.Click += new EventHandler(onMenuItemOpenLogClicked);
contextMenu.MenuItems.Add(menuItemOpenLog);
contextMenu.MenuItems.Add("-");
menuItemRunAtStartup = new MenuItem();
menuItemRunAtStartup.Index = 0;
menuItemRunAtStartup.Text = "Run at Windows startup";
menuItemRunAtStartup.Click += new EventHandler(onMenuItemRunAtStartupClicked);
menuItemRunAtStartup.Checked = settingsRunAtStartup;
contextMenu.MenuItems.Add(menuItemRunAtStartup);
contextMenu.MenuItems.Add("-");
menuItemExit = new MenuItem();
menuItemExit.Index = 1;
menuItemExit.Text = "E&xit";
menuItemExit.Click += new EventHandler(onMenuItemExitClicked);
contextMenu.MenuItems.Add(menuItemExit);
notifyIcon.ContextMenu = contextMenu;
updateContextMenu();
}
private void checkIfIdle(){
bool shouldWriteToLog = false;
if (!isUserIdle)
{
shouldWriteToLog = true;
}
// Primary idle check based on delay from users input
if (SystemHelper.GetIdleTime() >= configMgr.config.idleTime * 1000f)
{
// User is now idle
isUserIdle = true;
}
else
{
// User is not idle anymore
isUserIdle = false;
}
// Secondary idle check to see if the user is not using any input becaue he is watching a video or something
if (isUserIdle)
{
SystemHelper.GetPowerCfgOutput();
if (!SystemHelper.cannotGetPowercfg)
{
// Prase output of powercfg and find if monitor is being used.
// If not, detemine whether to consider user idle based on config.idleTime
if (SystemHelper.powerCfgOutput.IndexOf("DISPLAY:\r\nNone.") == -1)
{
//isUserIdle = false;
}
}
}
if (isUserIdle && shouldWriteToLog)
{
logMgr.logUserIdle();
}
}
/// <summary>
/// Main loop of the program that loops on timer
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void onTimer(object sender, EventArgs e)
{
checkIfIdle();
// Check the user process
if (!isUserIdle)
{
logMgr.checkForNewProcess();
}
//TCP Client Stuff
if (IPCSkipCount >= 3)//configMgr.config.TCPInterval)
{
if (isConnectedIPCServer)
{
connectedToIPCLabel.Text = "Connected to IPC: TRUE";
try
{
String receivedData = getDataFromIPCServer();
isConnectedIPCServer = true;
}
catch (Exception excep)
{
Console.WriteLine("Error..... " + excep.StackTrace);
//May be you got disconnected??
isConnectedIPCServer = false;
}
}
else
{
connectedToIPCLabel.Text = "Connected to IPC: FALSE";
numberOfTCPAttempts++;
if (numberOfTCPAttempts < configMgr.config.maxTCPAttempts) {
connectToIPCServer();
}
}
IPCSkipCount = 0;
}
else
{
IPCSkipCount++;
}
// Write to log if enough time passed
logMgr.checkIfShouldCommit();
}
private void initializeForm()
{
// Initialize
if (!hasInitialized)
{
// Read configuration
configMgr.readConfiguration();
// Initialize logging manager class through its constructor
logMgr = new LoggingManager(configMgr, this);
// Initialize power checker
Console.WriteLine("------------ MESSAGE --------------");
powerChecker = new PowerChecker();
allowClose = false;
isRunning = false;
allowShow = false;
// Force working folder
System.IO.Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
// Create context menu for the tray icon and update it
createContextMenu();
// Update tray
updateTrayIcon();
// Check if it needs to run at startup
applySettingsRunAtStartup();
// Finally, start
start();
hasInitialized = true;
}
}
private void start()
{
if (!isRunning)
{
// Initialize timer
timerCheck = new Timer();
timerCheck.Tick += new EventHandler(onTimer);
timerCheck.Interval = (int)(configMgr.config.timeCheckInterval * 1000f);
timerCheck.Start();
isRunning = true;
logMgr.fixedSizeLogQueue = new FixedSizedQueue<string>(Int32.Parse(configMgr.config.maxLogCache + ""));
//Log system start (Not really. This just means app started. BUT as I plan to run it on startup, this should be good)
logMgr.logLine("status::start");
connectToIPCServer();
updateContextMenu();
updateTrayIcon();
}
}
private void stop()
{
if (isRunning)
{
try
{
byte[] ba = asen.GetBytes("Logger::Shutting_Down");
stm.Write(ba, 0, ba.Length);
tcpclient.Close();
}
catch (Exception e)
{
Console.WriteLine("Error:: " + e.StackTrace);
}
logMgr.logStop();
timerCheck.Stop();
timerCheck.Dispose();
timerCheck = null;
isRunning = false;
updateContextMenu();
updateTrayIcon();
}
}
// Lable to show if there is any windows focused currently - TEMP. Should probably remove it from the final version as it barely gives any important info
public void changeFocusDebug(string text) {
focusDebug.Text = "Focused Window:" + text;
}
public void updateText(string text)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.labelApplication.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(updateText);
this.Invoke(d, new object[] { text });
}
else
{
labelApplication.Text = "Current App: " + text;
debugLogTextBox.AppendText(text + "\n");
}
}
private void applySettingsRunAtStartup()
{
// Check whether it's properly set to run at startup or not
if (settingsRunAtStartup)
{
// Should run at startup
if (!windowsRunAtStartup) windowsRunAtStartup = true;
}
else
{
// Should not run at startup
if (windowsRunAtStartup) windowsRunAtStartup = false;
}
}
private void showForm()
{
allowShow = true;
Show();
WindowState = FormWindowState.Normal;
}
private void exit()
{
allowClose = true;
Close();
}
private bool settingsRunAtStartup
{
// Whether the settings say the app should run at startup or not
get
{
return (bool)Settings.Default[SETTINGS_FIELD_RUN_AT_STARTUP];
}
set
{
Settings.Default[SETTINGS_FIELD_RUN_AT_STARTUP] = value;
Settings.Default.Save();
}
}
private void connectToIPCServer()
{
try
{
tcpclient = new TcpClient();
Console.WriteLine("Connecting.....");
tcpclient.Connect(configMgr.config.serverAddress, Int32.Parse(configMgr.config.serverPort + ""));
// use the ipaddress as in the server program
Console.WriteLine("Connected");
stm = tcpclient.GetStream();
isConnectedIPCServer = true;
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
}
}
private String getDataFromIPCServer()
{
String receivedData = "";
byte[] bb = new byte[100];
int k = stm.Read(bb, 0, 100);
if (k != 0)
{
receivedData = System.Text.Encoding.Default.GetString(bb);
byte[] ba = asen.GetBytes("Message Received. - Dhruv");
stm.Write(ba, 0, ba.Length);
}
return receivedData;
}
}
}