Click here to Skip to main content
15,888,610 members
Articles / Desktop Programming / MFC
Article

EXE Name From CWnd*

Rate me:
Please Sign up or sign in to vote.
2.60/5 (8 votes)
24 Jan 2005CPOL1 min read 49.6K   507   15   7
Retrieve executable name from CWnd.

Sample Image

Introduction

Recently, our company decided to produce a time management application. It was not enough for us to just know when people clocked in and clocked out, we wanted to know what they did while they were there. We decided that we would produce a timekeeping application which would allow us to track exactly what the user is doing while logged in. Initially, we thought we would record the title of the active window every second. This provided us more information than we wanted to know as well as made it cumbersome to do reporting on the data. We then decided it would be best to record just the executable name. I looked around for an article that I had seen before on how to do this, but it was not designed to run once a second. So I wrote this function which allows you to easily convert a CWnd* to the EXE name.

Using the code

The code is simple to use. The function GetWindowModuleName is passed a CWnd* and it returns the name of the executable.

#include "Psapi.h"

CString GetWindowModuleName(CWnd *pWnd)
{
    HMODULE* lphModule;
    char FileName[1024];
    DWORD procid = 0;
    DWORD modulesize = 0;
    BOOL bInheritHandle = false;

    if(pWnd != NULL){
        GetWindowThreadProcessId(pWnd->m_hWnd,&procid);
        HANDLE process = OpenProcess(PROCESS_ALL_ACCESS | 
           PROCESS_QUERY_INFORMATION, bInheritHandle,procid);
        if(process != NULL){
            lphModule = new HMODULE[1];
            if(EnumProcessModules(process,lphModule, 
                      (sizeof(HMODULE)),&modulesize) != 0){
                GetModuleBaseName(process,lphModule[0],FileName,1024);
                CloseHandle(process);
                delete lphModule;
                return FileName;
            }
            delete lphModule;
        }
        CloseHandle(process);
    }
    return "";
}

How does it work?

The function first calls the GetWindowThreadProcessId to get the current process ID. From there, we open the process and enumerate the process modules. The trick here is to send the EnumProcessModules function an array of HMODULE of length one. This will pull only the first module of the process which is the executable. Do not forget to include "Psapi.h" or link to Psapi.Lib.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer Logic Source
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralC# Pin
jlkdaslkfjd10-Jun-11 2:39
jlkdaslkfjd10-Jun-11 2:39 
QuestionDo you have a solution that can detect an window generated by a 64 bit system? Pin
dtgbrown4-May-09 15:52
dtgbrown4-May-09 15:52 
GeneralFor those who don't have the include file "Psapi.h" header file. Pin
spinoza2-Jun-05 21:38
spinoza2-Jun-05 21:38 
Try do load the Api with your own class: See below.

//////////////////////////////////////////////////////////////////////////////////////
//
// IPsapi.h
//
//////////////////////////////////////////////////////////////////////////////////////

class IPsapi
{
#if 0
#include <psapi.h>
#endif

#ifdef PROTECT_INTERFACES
friend BOOL GetProcessExecutableName( DWORD dwPID, LPTSTR szName, int cbSize );
protected:
#else
public:
#endif // ifdef PROTECT_INTERFACES

typedef struct _PROCESS_MEMORY_COUNTERS {
DWORD cb;
DWORD PageFaultCount;
SIZE_T PeakWorkingSetSize;
SIZE_T WorkingSetSize;
SIZE_T QuotaPeakPagedPoolUsage;
SIZE_T QuotaPagedPoolUsage;
SIZE_T QuotaPeakNonPagedPoolUsage;
SIZE_T QuotaNonPagedPoolUsage;
SIZE_T PagefileUsage;
SIZE_T PeakPagefileUsage;
} PROCESS_MEMORY_COUNTERS;
typedef PROCESS_MEMORY_COUNTERS *PPROCESS_MEMORY_COUNTERS;

typedef struct _MODULEINFO {
LPVOID lpBaseOfDll;
DWORD SizeOfImage;
LPVOID EntryPoint;
} MODULEINFO, *LPMODULEINFO;

typedef BOOL (WINAPI *PEnumProcesses)(
DWORD* lpidProcess, // array of process identifiers
DWORD cb, // size of array
DWORD* cbNeeded // number of bytes required
);

typedef BOOL (WINAPI *PGetProcessMemoryInfo)(
HANDLE Process, // handle to process
PPROCESS_MEMORY_COUNTERS ppsmemCounters, // buffer
DWORD cb // size of buffer
);

typedef BOOL (WINAPI *PEnumProcessModules)(
HANDLE hProcess, // handle to process
HMODULE* lphModule, // array of module handles
DWORD cb, // size of array
LPDWORD lpcbNeeded // number of bytes required
);

typedef DWORD (WINAPI *PGetModuleFileNameEx)(
HANDLE hProcess, // handle to process
HMODULE hModule, // handle to module
LPTSTR lpFilename, // path buffer
DWORD nSize // maximum characters to retrieve
);

typedef DWORD (WINAPI *PGetModuleBaseName)(
HANDLE hProcess, // handle to process
HMODULE hModule, // handle to module
LPTSTR lpBasename, // name buffer
DWORD nSize // maximum characters to retrieve
);

typedef BOOL (WINAPI *PGetModuleInformation)(
HANDLE hProcess, // handle to process
HMODULE hModule, // handle to module
LPMODULEINFO lpmodinfo, // info buffer
DWORD cb // info buffer size in bytes
);

typedef BOOL (WINAPI *PEnumDeviceDrivers)(
LPVOID* lpImageBase, // array of load addresses
DWORD cb, // size of array
LPDWORD lpcbNeeded // number of bytes returned
);

typedef DWORD (WINAPI *PGetDeviceDriverBaseName)(
LPVOID ImageBase, // driver load address
LPTSTR lpBaseName, // driver base name buffer
DWORD nSize // size of buffer
);

typedef DWORD (WINAPI *PGetDeviceDriverFileName)(
LPVOID ImageBase, // driver load address
LPTSTR lpFilename, // path buffer
DWORD nSize // size of buffer
);

typedef DWORD (WINAPI *PGetMappedFileName)(
HANDLE hProcess, // process handle
LPVOID lpv, // base address
LPTSTR lpFilename, // mapped file name
DWORD nSize // size of buffer
);

typedef DWORD (WINAPI *PGetProcessImageFileName)( // Windows XP+ !!!
HANDLE hProcess, // process handle
LPTSTR lpImageFileName, // process executable file name
DWORD nSize // size of buffer
);


static PEnumProcesses EnumProcesses;
static PGetProcessMemoryInfo GetProcessMemoryInfo;
static PEnumProcessModules EnumProcessModules;
static PGetModuleFileNameEx GetModuleFileNameEx;
static PGetModuleBaseName GetModuleBaseName;
static PGetModuleInformation GetModuleInformation;
static PEnumDeviceDrivers EnumDeviceDrivers;
static PGetDeviceDriverBaseName GetDeviceDriverBaseName;
static PGetDeviceDriverFileName GetDeviceDriverFileName;
static PGetMappedFileName GetMappedFileName;
static PGetProcessImageFileName GetProcessImageFileName;

static HMODULE hPsapi;
static BOOL PsapiStatus;

protected:
static BOOL Init();
};

//////////////////////////////////////////////////////////////////////////////////////
//
// IPsapi.cpp
//
//////////////////////////////////////////////////////////////////////////////////////
IPsapi::PEnumProcesses IPsapi::EnumProcesses = NULL;
IPsapi::PGetProcessMemoryInfo IPsapi::GetProcessMemoryInfo = NULL;
IPsapi::PEnumProcessModules IPsapi::EnumProcessModules = NULL;
IPsapi::PGetModuleFileNameEx IPsapi::GetModuleFileNameEx = NULL;
IPsapi::PGetModuleBaseName IPsapi::GetModuleBaseName = NULL;
IPsapi::PGetModuleInformation IPsapi::GetModuleInformation = NULL;
IPsapi::PEnumDeviceDrivers IPsapi::EnumDeviceDrivers = NULL;
IPsapi::PGetDeviceDriverBaseName IPsapi::GetDeviceDriverBaseName = NULL;
IPsapi::PGetDeviceDriverFileName IPsapi::GetDeviceDriverFileName = NULL;
IPsapi::PGetMappedFileName IPsapi::GetMappedFileName = NULL;
IPsapi::PGetProcessImageFileName IPsapi::GetProcessImageFileName = NULL; // Windows XP+

HMODULE IPsapi::hPsapi = NULL;
BOOL IPsapi::PsapiStatus = IPsapi::Init();

BOOL IPsapi::Init()
{
HMODULE hModule = LoadLibrary( _T("psapi.dll") );
hPsapi = hModule;

EnumProcesses = (PEnumProcesses)
GetProcAddress( hModule, "EnumProcesses" );

GetProcessMemoryInfo = (PGetProcessMemoryInfo)
GetProcAddress( hModule, "GetProcessMemoryInfo" );

EnumProcessModules = (PEnumProcessModules)
GetProcAddress( hModule, "EnumProcessModules" );

GetModuleFileNameEx = (PGetModuleFileNameEx)
GetProcAddress( hModule, "GetModuleFileNameEx" FUNC_SUFFIX );

GetModuleBaseName = (PGetModuleBaseName)
GetProcAddress( hModule, "GetModuleBaseName" FUNC_SUFFIX );

GetModuleInformation = (PGetModuleInformation)
GetProcAddress( hModule, "GetModuleInformation" );

EnumDeviceDrivers = (PEnumDeviceDrivers)
GetProcAddress( hModule, "EnumDeviceDrivers" );

GetDeviceDriverBaseName = (PGetDeviceDriverBaseName)
GetProcAddress( hModule, "GetDeviceDriverBaseName" FUNC_SUFFIX );

GetDeviceDriverFileName = (PGetDeviceDriverFileName)
GetProcAddress( hModule, "GetDeviceDriverFileName" FUNC_SUFFIX );

GetMappedFileName = (PGetMappedFileName)
GetProcAddress( hModule, "GetMappedFileName" FUNC_SUFFIX );

GetProcessImageFileName = (PGetProcessImageFileName)
GetProcAddress( hModule, "GetProcessImageFileName" FUNC_SUFFIX ); // Windows XP+


return EnumProcesses != NULL &&
GetProcessMemoryInfo != NULL &&
EnumProcessModules != NULL &&
GetModuleFileNameEx != NULL &&
GetModuleBaseName != NULL &&
GetModuleInformation != NULL &&
EnumDeviceDrivers != NULL &&
GetDeviceDriverBaseName != NULL &&
GetDeviceDriverFileName != NULL &&
GetMappedFileName != NULL &&
// GetProcessImageFileName != NULL && // Windows XP+
TRUE;
}
QuestionToo much access requested? Pin
Blake Miller26-Jan-05 8:36
Blake Miller26-Jan-05 8:36 
GeneralNot tricky at all Pin
<b>T</b>om <b>C</b>ollins24-Jan-05 22:54
<b>T</b>om <b>C</b>ollins24-Jan-05 22:54 
GeneralRe: Not tricky at all Pin
Diarrhio25-Jan-05 9:24
Diarrhio25-Jan-05 9:24 
GeneralRe: Not tricky at all Pin
<b>T</b>om <b>C</b>ollins25-Jan-05 23:38
<b>T</b>om <b>C</b>ollins25-Jan-05 23:38 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.