Hello MPGH members, today i want to show you how u can get the process ID of some process just by knowing it's name. It's quite simple just few lines of code .
Ok so first we need to include our headers and namespaces:
Code:
#include <windows.h>
#include <tlhelp32.h>
using namespace std;
I guess everyone knows for what windows.h is, and "tlhelp32.h" is needed for the snapshot function that we're gonna use to obtain the process id
So now let's define our function bellow the header:
Code:
#include <windows.h>
#include <tlhelp32.h>
using namespace std;
void GetProcId(char* ProcName);
What we just did is shown the compiler that this function exists, and when calling it we will have to give it 1 parameter: a char* variable that contains our process name . So next we will make the main() function and our "GetProcId" function bellow main.
Code:
#include <windows.h>
#include <tlhelp32.h>
using namespace std;
void GetProcId(char* ProcName);
int main()
{
return 0;
}
void GetProcId(char* ProcName)
{
PROCESSENTRY32 pe32;
HANDLE hSnapshot = NULL;
pe32.dwSize = sizeof( PROCESSENTRY32 );
hSnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );
if( Process32First( hSnapshot, &pe32 ) )
{
do{
if( strcmp( pe32.szExeFile, ProcName ) == 0 )
break;
}while( Process32Next( hSnapshot, &pe32 ) );
}
if( hSnapshot != INVALID_HANDLE_VALUE )
CloseHandle( hSnapshot );
ProcId = pe32.th32ProcessID;
}
So that's it all function we need. But notice on the last line there is:
Code:
ProcId = pe32.th32ProcessID;
You don't see that variable any ware ? Oh yes we forgot to declare it. Were gonna declare it as a GLOBAL variable right above main like so:
Code:
#include <windows.h>
#include <tlhelp32.h>
using namespace std;
void GetProcId(char* ProcName);
DWORD ProcId = 0; // THIS IS OUR GLOBAL VARIABLE FOR THE PROC ID;
int main()
{
return 0;
}
void GetProcId(char* ProcName)
{
PROCESSENTRY32 pe32;
HANDLE hSnapshot = NULL;
pe32.dwSize = sizeof( PROCESSENTRY32 );
hSnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );
if( Process32First( hSnapshot, &pe32 ) )
{
do{
if( strcmp( pe32.szExeFile, ProcName ) == 0 )
break;
}while( Process32Next( hSnapshot, &pe32 ) );
}
if( hSnapshot != INVALID_HANDLE_VALUE )
CloseHandle( hSnapshot );
ProcId = pe32.th32ProcessID;
}
1 last thing we need to do. We'll make it so The user to type the name of the process and the program to get the process ID . Let's do it !
In the main function:
Code:
int main()
{
char* ProcName;
cout << "Please type the process name" << endl;
cin >> ProcName >> endl;
GetProcId(ProcessName);
printf("The Process ID of " ProcName " is %d", ProcId);
cin.get() // to keep console open till we press a key
return 0;
}
And that's all hope u liked it