69,377
社区成员
发帖
与我相关
我的任务
分享
#include <windows.h>
#include <stdio.h>
#include <string.h>
#include <TlHelp32.h>
#include <tchar.h>
DWORD GetProcessIdByName(LPCTSTR szProcessName)
{
PROCESSENTRY32 pe32;
HANDLE hSnapshot;
ZeroMemory(&pe32, sizeof(PROCESSENTRY32));
pe32.dwSize = sizeof(PROCESSENTRY32);
hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (INVALID_HANDLE_VALUE == hSnapshot)
{
return FALSE;
}
if (!Process32First(hSnapshot, &pe32))
{
return FALSE;
}
do
{
if (0 == lstrcmpi(pe32.szExeFile, szProcessName))
{
CloseHandle(hSnapshot);
return pe32.th32ProcessID;
}
} while (Process32Next(hSnapshot, &pe32));
CloseHandle(hSnapshot);
return FALSE;
}
int main()
{
TCHAR szProcessName[MAX_PATH] = { 0 };
DWORD dwPID;
while (wscanf(_T("%ls"),szProcessName ))
{
dwPID = GetProcessIdByName(szProcessName);
wprintf(_T("The id of the process %s is %d\n"), (TCHAR*)szProcessName, dwPID);
}
return 0;
}
#include <locale.h> //头文件
setlocale (LC_ALL,""); //添加到main函数的第一行
原因是因为执行字符集和控制台字符集必须保持一致(GBK)。
代码中setlocale (LC_ALL,"");的作用是将执行字符集与操作系统的字符集设置成一样。
更详细的原因请查询相关资料,可以从setlocale函数入手: