views:

915

answers:

2

Hi

When I call GetForegroundWindow from c# I am getting the explorer parent process ID (I see this from process explorer) and not the process ID of the app that is in the foreground.

Why is this and how do get the right process ID?

Malcolm

A: 

Not sure what's happening here, but have you tried running your app as Administrator? There are now lots of restrictions about what non-admin apps are able to see across the rest of the system.

Will Dean
+4  A: 

The API function GetForegroundWindow gets you a handle to the top window, not the process ID. So what other functions do you use to get the process ID from the window handle you get from GetForegroundWindow?

This will get you the WINDOW HANDLE of the foreground window:

    [DllImport("user32", SetLastError = true)]
    public static extern int GetForegroundWindow();

This will get you the Process ID (PID in taskmgr) of a given WINDOW HANDLE:

    [DllImport("user32", SetLastError = true)]
    public static extern int GetWindowThreadProcessId(int hwnd, ref int lProcessId);

    public static int GetProcessThreadFromWindow(int hwnd) {
        int procid = 0;
        int threadid = GetWindowThreadProcessId(hwnd, ref procid);
        return procid;
    }

It'd be nice if you responded back on your question so it has some value on this forum.

Wolf5