First, call CreateToolhelp32Snapshot () to get a snapshot of the currently running process, which returns the snapshot handle that contains the running process. Its prototype is:
HANDLE WINAPI CreateToolhelp32Snapshot (DWORD dwflags,dword th32processid);
which
dwflags indicates that the content to be included in the snapshot is th32cs_snapprocess to include the list of processes in the snapshot;
Th32processid is the process number, and 0 represents the current process.
The return value is a handle that, if no process is running, returns INVALID_HANDLE_VALUE (available GetLastError ()), whereas the bool WINAPI Process32First (HANDLE hsnapshot, LPPROCESSENTRY32 Lppe); Get the returned process
If Process32First returns True, the information for the first process is already in the LPPROCESSENTRY32 structure, and the rest of the process information is available in BOOL WINAPI Process32Next (HANDLE hsnapshot, LPPROCESSENTRY32 Lppe) obtained
The LPPROCESSENTRY32 structure is defined as follows:
typedef struct tagPROCESSENTRY32 {
DWORD dwSize; //此结构的大小
DWORD cntUsage; //进程的引用数,如果为0,则次进程已停止
DWORD th32ProcessID; //进程号
ULONG_PTR th32DefaultHeapID;
DWORD th32ModuleID; //此进程引用的模块ID
DWORD cntThreads; //此进程创建的线程数
DWORD th32ParentProcessID; //父进程的ID
LONG pcPriClassBase; //这个进程创建的线程的基本优先权
DWORD dwFlags; //保留
TCHAR szExeFile[MAX_PATH];
} PROCESSENTRY32;
typedef PROCESSENTRY32 *PPROCESSENTRY32;
Finally, don't forget to call:
CloseHandle();
The other function is:
HANDLE OpenProcess(
DWORD dwDesiredAccess, // access flag
BOOL bInheritHandle, // handle inheritance option
DWORD dwProcessId // process identifier
);
With it, you can open a process, and after you open the process, you can use:
BOOL TerminateProcess(
HANDLE hProcess, // handle to the process
UINT uExitCode // exit code for the process
);
To close the process.
The author uses the above function to do a process manager like Task Manager to enumerate all processes and close processes. See source code for details.
This article supporting source code