Question : Get active application name

How do I get the current active application's exe name. I have tried GetForegroundWindow but this only works if my application is active. I want to get the name of the application that has focus.

For instance if SQL Server has focus, I want my application to return "MS SQL Server" as the exe name.

Answer : Get active application name

Hi,

I don't think 'GetFocus' will help since it only returns a valid handle if the window which has the focus is running in the same process as the application which calls 'GetFocus'.

You can use 'GetGUIThreadInfo' to obtain a handle of the window which has the focus even if it's a window from another process, i.e.:

> // 1. find window which currently has the focus
> GUITHREADINFO info = { sizeof( GUITHREADINFO ) };
> if ( FALSE != ::GetGUIThreadInfo( NULL, &info ) )
> {
>  HWND hWnd = info.hwndFocus;
> }

Next, to find the name of the EXE file of the process to which this window belongs IMO you can only use the PSAPI function GetModuleFileNameEx. This needs a handle to the process. You can do it somehow like this:

> // 2. retrieve the process ID
> DWORD dwProcessId;
> GetWindowThreadProcessId( hWnd, &dwProcessId );

> // 3. open a process handle
> HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, dwProcessId );

> // 4. obtain the EXE's name
> char pszExe[ _MAX_PATH ];
> GetModuleFileNameEx( hProcess, NULL, pszExe, sizeof( pszExe ) );

> // 5. don't forget to close the process handle
> CloseHandle( hProcess );

Notes:
- you need to add error checking code for all of these steps.

- even this method doesn't work for all applications, I think it depends on the security privileges the current user has - i.e. on Windows Vista (where I tested this) 'GetModuleFileNameEx' for lot of applications (like explorer.exe, taskman.exe, regedit.exe) failed with error code 299 (ERROR_PARTIAL_COPY) - maybe this can be solved by adjusting the current users privilieges, but this is quite another task - and you may find a lot of samples anywhere.

- to use PSAPI you need to add the appropriate header/lib, i.e. this way:
> #include "psapi.h"
> #pragma comment ( lib, "Psapi.lib" )


Hope that helps,

ZOPPO


Random Solutions  
 
programming4us programming4us