How can I get the process name from the foreground window on Windows using Java?
<p>I'm trying to get the name of the process from the foreground window, but I have some problems. </p>

<p>For example, if I open Mozilla firefox, it registers something like "www.google.com - Mozilla Firefox". In photoshop, it registers "filename.psd" + the zoom or the layer name you're working on.</p>

<p>I want to get the process name from the foreground window, I don't want it to detect every layer you're working on, etc, I just want it to get the process name (photoshop.exe or something like that)</p>

<p>For now, I'm using this to get the foreground window name and the ID of the process from that window:</p>

<pre><code>public String getActiveProcess(){                   
    char[] buffer;
    HWND hwnd;
    String processName = ".... // ";
    IntByReference IdByRef = new IntByReference();

    //get window information
    buffer = new char[MAX_TITLE_LENGTH * 2];
    hwnd = User32.INSTANCE.GetForegroundWindow();

    //get process ID from window in foreground
    int processid = User32.INSTANCE.GetWindowThreadProcessId(hwnd, IdByRef);

    HANDLE processHandle = Kernel32.INSTANCE.OpenProcess(processid, true, MAX_TITLE_LENGTH);

    return processName;     
}
</code></pre>