Skip to content

Instantly share code, notes, and snippets.

@sparksbat
Created October 24, 2017 21:23
Show Gist options
  • Save sparksbat/38d3a8c31f36d18cc497831631691067 to your computer and use it in GitHub Desktop.
Save sparksbat/38d3a8c31f36d18cc497831631691067 to your computer and use it in GitHub Desktop.
C# Get Foreground Process
using System;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace FGWindow
{
class ProcessUtils
{
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", SetLastError = true)]
static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
public static Process getForegroundProcess()
{
uint processID = 0;
IntPtr hWnd = GetForegroundWindow(); // Get foreground window handle
uint threadID = GetWindowThreadProcessId(hWnd, out processID); // Get PID from window handle
Process fgProc = Process.GetProcessById(Convert.ToInt32(processID)); // Get it as a C# obj.
// NOTE: In some rare cases ProcessID will be NULL. Handle this how you want.
return fgProc;
}
}
}
using System;
using System.Diagnostics;
using System.Threading;
namespace FGWindow
{
class Program
{
static void Main(string[] args)
{
while (true)
{
// This is how you call the GetFGProcess stuff.
Process fgProc = ProcessUtils.getForegroundProcess();
Console.WriteLine(fgProc.ProcessName);
Thread.Sleep(5000);
}
}
}
}
@SaxPlay
Copy link

SaxPlay commented Apr 5, 2021

Works like charm.. Thank you so much!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment