判断进程是否存在

#include
#include
#include

char output[256];

DWORD GetProcessidFromName(LPCTSTR name)
{
PROCESSENTRY32 pe;
DWORD id=0;
HANDLE hSnapshot=CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
pe.dwSize=sizeof(PROCESSENTRY32);
if(!Process32First(hSnapshot,&pe))
    return 0;
    //LPCTSTR转char*
    int num = WideCharToMultiByte(CP_OEMCP,NULL,name,-1,NULL,0,NULL,FALSE);
    char *pchar = new char[num];
    WideCharToMultiByte (CP_OEMCP,NULL,name,-1,pchar,num,NULL,FALSE);

    while(1)
    {
        pe.dwSize=sizeof(PROCESSENTRY32);

        //一个进程接一个进程直到结束
        if(Process32Next(hSnapshot,&pe)==FALSE)
            break;

       //WCHAR 转char*
        WCHAR* wc = pe.szExeFile ;
        sprintf(output, "%ws", wc );


        if(strcmp(output,pchar)==0)
        {
            id=pe.th32ProcessID;
    
            break;
        }
 
 
    }
CloseHandle(hSnapshot);
return id;
}

int main()
{

  //是0就不存在进程,返回非0就是存在
    int id=GetProcessidFromName(TEXT("lsass.exe"));
    std::cout<     while(1);
}

你可能感兴趣的:(Windows,api)