win32进程名查找进程PID

1.

#include <Psapi.h>
#pragma comment(lib, "Psapi.lib")
DWORD GetProcIDFromName(LPCTSTR lpName)
{
    DWORD aProcId[1024], dwProcCnt, dwModCnt;
    HMODULE hMod;
    TCHAR szPath[MAX_PATH];

    //枚举出所有进程ID
    if (!EnumProcesses(aProcId, sizeof(aProcId), &dwProcCnt)){
        //cout << "EnumProcesses error: " << GetLastError() << endl;
        return 0;
    }

    //遍例所有进程
    for (DWORD i = 0; i < dwProcCnt; ++i)
    {
        //打开进程,如果没有权限打开则跳过
        HANDLE hProc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, aProcId[i]);
        if (NULL != hProc)
        {
            //打开进程的第1个Module,并检查其名称是否与目标相符
            if (EnumProcessModules(hProc, &hMod, sizeof(hMod), &dwModCnt))
            {
                GetModuleBaseName(hProc, hMod, szPath, MAX_PATH);
                if (0 == lstrcmpi(szPath, lpName))
                {
                    CloseHandle(hProc);
                    return aProcId[i];
                }
            }
            CloseHandle(hProc);
        }
    }
    return 0;
}

2.

#include <Tlhelp32.h>
BOOL GetProcessIdByName(LPCTSTR lpszProcessName, PDWORD pdwProcessId)
{
    *pdwProcessId = 0;
    HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if (hSnapshot == INVALID_HANDLE_VALUE)
    {
        return FALSE;
    }

    PROCESSENTRY32 pe;
    pe.dwSize = sizeof pe;

    if (Process32First(hSnapshot, &pe))
    {
        do {
            if (lstrcmpi(lpszProcessName, pe.szExeFile) == 0)
            {
                CloseHandle(hSnapshot);
                *pdwProcessId = pe.th32ProcessID;
                return TRUE;
            }
        } while(Process32Next(hSnapshot, &pe));
    }

    CloseHandle(hSnapshot);
    return FALSE;
}

 独立调用此函数时会返回空,在IDE下却可以,这就需要提权了,提权参考Win32 OpenProcess打开进程失败,返回5无权限操作

posted @ 2014-10-13 16:25  小孟文摘  阅读(1983)  评论(0编辑  收藏  举报