The functions used in the previous chapter are complex, and this chapter uses the process ID number directly and uses the Getmodulefilenameex function to achieve process path acquisition.
#include "stdafx.h"
#include <windows.h>
#include "stdio.h"
#include <tlhelp32.h>
#include "Psapi.h"
int _tmain (int argc, _tchar* argv[])
{
int num=0;
TCHAR exe_name[20]=_t ("Notepad++.exe");//process name to query
TCHAR Pszfullpath[max_path];
PROCESSENTRY32 pe32;//structure for storing process information
HANDLE Hprocesssnap=::createtoolhelp32snapshot (th32cs_snapprocess,0);//Create a process snapshot
Pe32.dwsize=sizeof (PE32);
if (Hprocesssnap==invalid_handle_value)
{
printf ("CreateToolhelp32Snapshot failed!\n");
return-1;
}
BOOL bmore=::P rocess32first (HPROCESSSNAP,&PE32);//Get the first process information into the PE32 structure
while (bmore)
{
printf ("Name is:%ls\n", pe32.szexefile);
printf ("num is:%d\n", num);
printf ("ID is:%d\n", pe32.th32processid);
if (!_tcscmp (exe_name,pe32.szexefile))//Discovery to find the process after end lookup
{
printf ("Find the file you want:%ls\n", pe32.szexefile);
Break
}
num++;
Bmore=::P rocess32next (HPROCESSSNAP,&PE32);
}
if (!_tcscmp (exe_name,pe32.szexefile))
{
HANDLE hprocess = OpenProcess (PROCESS_ALL_ACCESS,FALSE,PE32.TH32PROCESSID);
TCHAR pbuffer[max_path+1];
Getmodulefilenameex (hprocess,null,pbuffer,max_path+1);//Use the Getmodulefilenameex function to get the process file path directly
printf ("File name is:%ls\n\n", pbuffer);
HANDLE hprocess=::openprocess (PROCESS_ALL_ACCESS,FALSE,PE32.TH32PROCESSID);
if (hprocess!=null)
{
:: TerminateProcess (hprocess,0);//Close process
printf ("I had close the process you choose!\n");
:: CloseHandle (hprocess);
}
}
CloseHandle (HPROCESSSNAP);
GetChar ();//Let the program have input at the end
return 0;
}
C + + process detection, discovery process path, shutdown process (ii)