Re: To get ProcessID from ProcessName.
"veethappi" <abcd@dc.com> wrote in message
news:BA99E908-14B7-44E6-9F67-0DA5346A69B3@microsoft.com...
Hi,
I have an application where the requirement is to get a Processid from the
process name. Say the process name that is running in the system is
Notepad.exe, I need to capture processid of Notepad.exe.
For this we have implemented an approach. But this approach is failing in
some systems.
Use the ToolHelp API to create a snapshot of processes:
DWORD FindProcessId (LPCSTR pAppName)
{
// Search for a process with same name as pAppName
// and return it's ID.
OSVERSIONINFO VerInfo;
VerInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
GetVersionEx (&VerInfo);
BOOL bWin2k = ((VerInfo.dwMajorVersion == 5) && (VerInfo.dwMinorVersion ==
0)); // Win2K
// Determine all processes in the system at this instant:
DWORD dwProcessId = 0;
HANDLE hSnapshotProcess = CreateToolhelp32Snapshot (TH32CS_SNAPPROCESS, 0);
// Find filename.ext of pAppName:
LPTSTR pAppFileName = PathFindFileName (pAppName);
// Enumerate all the processes, searching for ones corresponding to
pAppName:
PROCESSENTRY32 pe;
pe.dwSize = sizeof(pe);
for ( BOOL bMoreProcesses = Process32First (hSnapshotProcess, &pe);
bMoreProcesses && !dwProcessId;
bMoreProcesses = Process32Next (hSnapshotProcess, &pe) )
{
LPCTSTR pExePath = pe.szExeFile;
if (bWin2k)
{
// A bug in Win2K truncates pe.szExeFile to 15 characters! But the first
modulename
// is the full path to the .exe. Use that instead:
if ( pe.th32ProcessID != 0 ) // not special system process, whose first
module can be anything
{
// safe to call Module32First and not have it accidentally match
HANDLE hSnapshotModule = CreateToolhelp32Snapshot (TH32CS_SNAPMODULE,
pe.th32ProcessID);
MODULEENTRY32 me;
me.dwSize = sizeof(me);
Module32First (hSnapshotModule, &me);
pExePath = me.szModule;
CloseHandle (hSnapshotModule);
}
}
// Win9x reports full path name; isolate this process's filename.ext:
LPTSTR pExeFileName = PathFindFileName (pExePath);
if ( lstrcmpi (pAppFileName, pExeFileName) == 0 ) // filenames match
{
// no callback, return this process
dwProcessId = pe.th32ProcessID;
}
}
CloseHandle (hSnapshotProcess);
return dwProcessId;
}
-- David