I have googled for several hours and tried everything I found, but it just doesn't seem to work.
My code is:
private static long _i;
private static readonly System.Timers.Timer Timer = new System.Timers.Timer(1000);
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
private static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
[DllImport("user32.dll")]
private static extern int GetWindowModuleFileName(IntPtr hWnd, StringBuilder text, int count);
static void Main()
{
Timer.Elapsed += Timer_Elapsed;
Timer.AutoReset = true;
Timer.Start();
while (Timer.Enabled)
Console.ReadLine();
}
static void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
Console.WriteLine("-|- - " + _i + " - -|-");
Console.WriteLine("WindowHandle: " + GetForegroundWindow());
var buff = new StringBuilder(2048);
GetWindowModuleFileName(GetForegroundWindow(), buff, 1024);
Console.WriteLine("ModuleName: " + Path.GetFileName(buff.ToString()));
Console.WriteLine("-|- - | - -|-");
_i++;
}
The output of this code is always something like this:
-|- - 1 - -|-
WindowHandle: 8128962
ModuleName: ConsoleApplication.vshost.exe
-|- - | - -|-
But even when I target another application like Chrome or Fiddler, it always prints out my executable filename or no filename at all. Is there a problem I might be missing?