-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
80 lines (67 loc) · 2.49 KB
/
Program.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
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
namespace WinFocusLogger;
public static partial class Program
{
[LibraryImport("user32.dll")]
private static partial IntPtr GetForegroundWindow();
[LibraryImport("user32.dll")]
private static partial uint GetWindowThreadProcessId(IntPtr hWnd, out uint processId);
public static void Main()
{
uint lastActiveProcId = 0;
uint activeProcId = 0;
var program = new StringBuilder();
var programName = new StringBuilder();
var buffer = new StringBuilder();
Console.WriteLine("{0,-25} {1,-10} {2,-20} {3,-0}\n", "Name", "PID", "Date", "Location");
while (true)
{
Thread.Sleep(100);
if (GetForegroundWindow() != IntPtr.Zero)
{
if (GetWindowThreadProcessId(GetForegroundWindow(), out activeProcId) == 0) continue;
if (activeProcId == 0)
{
Console.WriteLine($"GetWindowThreadProcessId had error {Marshal.GetLastWin32Error()}");
continue;
}
Process hProc;
try
{
hProc = Process.GetProcessById((int)activeProcId);
}
catch (Win32Exception e)
{
Console.WriteLine($"GetProcessByID had error {e.NativeErrorCode}");
continue;
}
try
{
if (hProc.MainModule != null)
{
program.Clear();
program.Append(hProc.MainModule.FileName);
}
}
catch (Win32Exception e)
{
Console.WriteLine($"MainModule.FileName had error {e.NativeErrorCode}");
continue;
}
if (hProc.MainModule != null)
{
programName.Clear();
programName.Append(hProc.ProcessName);
}
}
if (activeProcId == lastActiveProcId || activeProcId == 0) continue;
buffer.Clear();
buffer.Append($"{DateTime.Now:yy-MMM-dd HH:mm:ss}");
Console.WriteLine("{0,-25} {1,-10} {2,-20} {3,-0}", programName, activeProcId.ToString(), buffer, program);
lastActiveProcId = activeProcId;
}
}
}