With only 70 lines of code, teach you to traverse all processes in current windows!

Hello, everyone, I am KookNut39, I write an article in CSDN, share some things that I think are more important in the learning process, I hope it can help you make progress. I have recently updated the knowledge of C/C++. If you are interested, please follow the bloggers and check the previous articles in the column. I hope to discuss the technology with you in the future.

I believe that for many students who are learning C++, a question that is more puzzled at the beginning stage is, what can I do with this thing? Is it to output "Hello World"? It seems that I have learned a lot of things and I feel like I have learned a lot, and I don't know what I can do. I know variables, data structures, classes, pointers, and STL standard template library teachers. But what can these things do together?

Insert picture description here

Today, let kt bring you hands-on practice, in order to increase your enthusiasm for learning, write a piece of code C/C++ code on the windows system to achieve all process traversal, which is a bankrupt beggar version of the task manager .
By default, everyone has mastered a certain level of C/C++ programming, but it does not matter if the mastery is not high. Follow the steps and you can definitely realize the operation of process traversal .

Let's start with the main function:

int main()
{
	//设置地域化信息,设置中文,能够识别中文
	setlocale(LC_ALL, "chs");
	char* v1 = (char*)("进程枚举:");
	printf("%s\n", v1);
	//枚举进程的函数
	EnumSystemProcess();
	system("pause");
	system("cls");
	system("pause");
	return 0;
}

First, we call a setlocale function to set localization information in the main function, because we want to output Chinese in the text. The next step is to print a string, these are not important codes, and then call the EnumSystemProcess() function, which is a self-implemented function, starting from here to traverse the process:

//枚举系统进程  拍摄快照
	HANDLE SnapHandle = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
	if (SnapHandle == INVALID_HANDLE_VALUE)
	{
		return;
	}

This is the first thing EnumSystemProcess needs to do, that is, to take a system snapshot. The function to take a system snapshot is CreateToolhelp32Snapshot. When the parameter is TH32CS_SNAPPROCESS, it will return the handle of the process snapshot. Next:

	//PROCESSENTRY32 必须这样初始化
	PROCESSENTRY32 ProcessEntry = { sizeof(PROCESSENTRY32) };
	bool IsOk = ProcessFirst(SnapHandle, &ProcessEntry);

PROCESSENTRY32 is a system structure contained in the tlhelp32.h header file, which contains this information:

typedef struct tagPROCESSENTRY32
{
    DWORD   dwSize;
    DWORD   cntUsage;
    DWORD   th32ProcessID;          // this process
    ULONG_PTR th32DefaultHeapID;
    DWORD   th32ModuleID;           // associated exe
    DWORD   cntThreads;
    DWORD   th32ParentProcessID;    // this process's parent process
    LONG    pcPriClassBase;         // Base priority of process's threads
    DWORD   dwFlags;
    CHAR    szExeFile[MAX_PATH];    // Path
} PROCESSENTRY32;

The official structure of the key fields has been commented, what we need to use is to take th32ProcessID and szExeFile, because we only print the process name and process ID.
Then there is the ProcessFirst function, which is my self-implemented function, in which the

Insert picture description here


process ID is 0 in order to bypass the system idle process :

BOOL ProcessFirst(HANDLE SnapHandle, PPROCESSENTRY32 ProcessEntry)
{

	BOOL IsOk = Process32First(SnapHandle, ProcessEntry);
	if (IsOk && (ProcessEntry->th32ProcessID == 0))
	{
		//如果PID = 0,那就byebye  继续去找下一个进程的ProcessEntry
		IsOk = ProcessNext(SnapHandle, ProcessEntry); 
	}
	return IsOk;
}

Then call the Process32First system function in it, in order to get the ProcessEntry of the first process, if the current process id is 0, then continue to traverse to find the next process:

BOOL ProcessNext(HANDLE SnapHandle, PPROCESSENTRY32 ProcessEntry)
{

	BOOL IsOk = Process32Next(SnapHandle, ProcessEntry);
	if (IsOk && (ProcessEntry->th32ProcessID == 0))
	{
		//递归调用
		IsOk = ProcessNext(SnapHandle, ProcessEntry);
	}
	return IsOk;
}

Here we call Process32Next to get the PPROCESSENTRY32 structure information of the next process, and then perform ID judgment. If it is not ID=0, then return. Return to the call of EnumSystemProcess, and then execute the for loop to traverse and print.

	//索引 为了统计当前进程总数
	int  Index = 0;
	for (; IsOk; IsOk = ProcessNext(SnapHandle, &ProcessEntry))
	{
		char BufferData[1024];
		//c:\\windows\\hello.exe  寻找'\\'最后出现的位置
		char* ProcessName = strrchr(ProcessEntry.szExeFile, '\\');
		if (ProcessName == NULL)
		{
			ProcessName = ProcessEntry.szExeFile;
		}
		else
		{
			ProcessName++;   //越过反斜杠
		}
		sprintf(BufferData, "%-50s%     (0x%08X)", ProcessName, ProcessEntry.th32ProcessID);
		printf("%s\n", BufferData);
		Index++;
	}
	printf("当前系统进程总共有 %d 个\n", Index);

Let's take a look at the renderings:

Insert picture description here

The realization of the entire traversal process is over here. If you still don’t know anything, it’s okay, you can contact me at any time and I will help you to answer, or if you have a small partner who needs the source code, you can also ask me to take you!

Insert picture description here
I like the blogger’s article, please give me a one-click three-link support 🤞🤞🤞, your support is my biggest creative motivation!

Today's share of encouragement: "Meeting the spirits is the king's drink, the horse is by the weeping willow of the tall building"