Windows 获取进程ID
DWORD GetProcessID(const char *ProcessName)
{
PROCESSENTRY32 pe32;
pe32.dwSize = sizeof(PROCESSENTRY32);
//获取进程快照
HANDLE hProcessSnap = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hProcessSnap == INVALID_HANDLE_VALUE)
{
printf("CreateToolhelp32Snapshot 调用失败.\n");
return -1;
}
//遍历进程快照,轮流显示每个进程的信息
BOOL bMore = ::Process32First(hProcessSnap, &pe32);
while (bMore)
{
printf("进程名称:%ls\n", pe32.szExeFile); //这里得到的应该是宽字符,用%ls,不然无法正常打印
printf("进程ID:%u\n\n", pe32.th32ProcessID);
if (lstrcmp(pe32.szExeFile, ProcessName) == 0)
{
break;
}
bMore = ::Process32Next(hProcessSnap, &pe32);
}
//不要忘记清除掉snapshot对象
::CloseHandle(hProcessSnap);
return pe32.th32ProcessID;
}
int main()
{
DWORD ID;
const char *name = "sscom32.exe";
ID = GetProcessID(name);
printf("GetProcessId %s %u\n", name, ID);
while (1);
return 0;
}
需要配置
或者
DWORD GetProcessID(LPCWSTR ProcessName)
{
PROCESSENTRY32 pe32;
pe32.dwSize = sizeof(PROCESSENTRY32);
//获取进程快照
HANDLE hProcessSnap = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hProcessSnap == INVALID_HANDLE_VALUE)
{
printf("CreateToolhelp32Snapshot 调用失败.\n");
return -1;
}
//遍历进程快照,轮流显示每个进程的信息
BOOL bMore = ::Process32First(hProcessSnap, &pe32);
while (bMore)
{
//printf("进程名称:%ls\n", pe32.szExeFile); //这里得到的应该是宽字符,用%ls,不然无法正常打印
//printf("进程ID:%u\n\n", pe32.th32ProcessID);
if (lstrcmp(pe32.szExeFile, ProcessName) == 0)
{
break;
}
bMore = ::Process32Next(hProcessSnap, &pe32);
}
//不要忘记清除掉snapshot对象
::CloseHandle(hProcessSnap);
return pe32.th32ProcessID;
}
int main()
{
DWORD ID;
LPCWSTR name = _T("sscom32.exe");
ID = GetProcessID(name);
printf("GetProcessId %ls %u\n", name, ID);
while (1);
return 0;
}