How to Get Active Process Name in C#?

As mentioned in this answer, you have to use GetWindowThreadProcessId() to get the process id for the window and then you can use the Process:

[DllImport("user32.dll")]
public static extern IntPtr GetWindowThreadProcessId(IntPtr hWnd, out uint ProcessId);

[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();

string GetActiveProcessFileName()
{
    IntPtr hwnd = GetForegroundWindow();
    uint pid;
    GetWindowThreadProcessId(hwnd, out pid);
    Process p = Process.GetProcessById((int)pid);
    p.MainModule.FileName.Dump();
}

Be aware that this seems to throw an exception (“A 32 bit processes cannot access modules of a 64 bit process”) when run from a 32-bit application when the active process is 64-bit.

EDIT: As Damien pointed out, this code is prone to race conditions, because the process that had the active window at the time when GetForegroundWindow() was called might not exist anymore when GetWindowThreadProcessId() is called. Even worse situation would be if the same hwnd would be assigned to another window at that time, but I guess this should be really rare.

Leave a Comment