Friday, April 3, 2015

Visual C++ 실행파일 이름으로 프로세스 ID 얻기(EnumProcessModules)

#include "stdafx.h"
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include <psapi.h>

#pragma comment(lib, "Psapi.lib")

// To ensure correct resolution of symbols, add Psapi.lib to TARGETLIBS
// and compile with -DPSAPI_VERSION=1
bool CheckProcessIDByName(DWORD processID, LPCTSTR targetProcessName)
{
 TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>");

 // Get a handle to the process.
 HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION |
  PROCESS_VM_READ,
  FALSE, processID );

 // Get the process name.
 if (NULL != hProcess )
 {
  HMODULE hMod;
  DWORD cbNeeded;

  if ( EnumProcessModules( hProcess, &hMod, sizeof(hMod),
   &cbNeeded) )
  {
   GetModuleBaseName( hProcess, hMod, szProcessName,
    sizeof(szProcessName)/sizeof(TCHAR) );
  }
 }

 // Release the handle to the process.
 CloseHandle( hProcess );

 // Print the process name and identifier.
 //_tprintf( TEXT("%s  (PID: %u)\n"), szProcessName, processID );
 if(!wcsicmp(szProcessName, targetProcessName))
  return true;

 return false;
}
int FindProcessIDByName(LPCTSTR targetProcessName)
{
 DWORD aProcesses[1024], cbNeeded, cProcesses;
 unsigned int i;
 if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) )
 {
  return 0;
 }
 // Calculate how many process identifiers were returned.
 cProcesses = cbNeeded / sizeof(DWORD);

 for ( i = 0; i < cProcesses; i++ )
 {
  if( aProcesses[i] != 0 )
  {
   if(CheckProcessIDByName(aProcesses[i], targetProcessName) )
   {
    return aProcesses[i];
   }

   //PrintProcessNameAndID( aProcesses[i] );
  }
 }
 return 0;
}

int _tmain(int argc, _TCHAR* argv[])
{
 int testProcId = FindProcessIDByName(L"test.exe");
 return 0;
}

No comments:

Post a Comment