[C++] Get process ID based on process name

1. Function description

Function name illustrate
1 GetProcessIdFromName() Under Windows, search for a process based on its name. If it is found, the PID is returned. If it is not found, it returns -2;

2. Code

Description: Get the process ID based on the process name

#include <iostream>
#include <windows.h>  
#include <TlHelp32.h> 
#include <comdef.h>
using namespace std;

long GetProcessIdFromName(const char *name)
{
    
    
	HANDLE hsnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
	if (hsnapshot == INVALID_HANDLE_VALUE)
	{
    
    
		cout << "Create TlHelp32 Error!" << endl;
		return -1;
	}

	PROCESSENTRY32 processer;
	processer.dwSize = sizeof(PROCESSENTRY32);

	int flag = Process32First(hsnapshot, &processer);
	while (flag != 0)
	{
    
    
		_bstr_t processName(processer.szExeFile);  //WCHAR字符串转换成CHAR字符串
		if (strcmp(processName, name) == 0)
		{
    
    
			return processer.th32ProcessID;        //返回进程ID
		}
		flag = Process32Next(hsnapshot, &processer);
	}

	CloseHandle(hsnapshot);
	return -2;
}

int main()
{
    
    
	long pid = GetProcessIdFromName("DeepL.exe");  //输入进程名
	cout << "DeepL.exe pid : " << pid << endl;

	system("pause");
	return 0;
}

3. Convert WCHAR to CHAR

Convert WCHARstring to CHARstring:

#include<comdef.h>   //必须包含

const WCHAR* wchar = L"HelloWorld";

_bstr_t bchar(wchar);

const char* cchar = bchar;

If this article is helpful to you, I would like to receive a like from you!

Insert image description here

おすすめ

転載: blog.csdn.net/AAADiao/article/details/131578425