进程的查找、遍历与终止

查找进程中QQ进程并终止该进程

#include<windows.h>

#include<stdio.h>

#include<tlhelp32.h>

DWORD FindProcess(char * fileName)//查找进程

{

    PROCESSENTRY32 pe32={sizeof(PROCESSENTRY32)};

    HANDLE hSnapshot=CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);

    if(hSnapshot==INVALID_HANDLE_VALUE)

    {

        printf("获取进程快照失败!\n");

        return 0;

    }

    BOOL bMore = ::Process32First(hSnapshot,&pe32);

    while(bMore)

    {

        if(strcmp(pe32.szExeFile,fileName)==0) 

            return pe32.th32ProcessID;

        bMore = ::Process32Next(hSnapshot,&pe32);

    }

        ::CloseHandle(hSnapshot);

    return 0;

}

BOOL EnumProcess()//遍历进程

{

    PROCESSENTRY32 pe32={sizeof(PROCESSENTRY32)};

    HANDLE hSnapshot=CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);

    if(hSnapshot==INVALID_HANDLE_VALUE)

    {

        printf("获取进程快照失败\n");

        return 0;

    }

    BOOL bMore=::Process32First(hSnapshot,&pe32);

    while(bMore)

    {

        printf("进程号:%d,进程名:%s\n",pe32.th32ProcessID,pe32.szExeFile);

        bMore=::Process32Next(hSnapshot,&pe32);

    }

    ::CloseHandle(hSnapshot);

    return 1;

}

int main(int argc,char * argv[])

{

    DWORD exitCode;

    char fileName[]="QQ.exe";

    //EnumProcess();

    DWORD handleId=FindProcess(fileName);

    if(handleId==0)

    {

        printf("没有找到%s进程\n",fileName);

        return 0;

    }

    HANDLE hProcess=OpenProcess(PROCESS_ALL_ACCESS,FALSE,handleId);

    if(hProcess!=NULL)

    {

                GetExitCodeProcess(hProcess,&exitCode);

                ::TerminateProcess(hProcess,exitCode);

        printf("成功关闭%s进程\n",fileName);

    }

        handleId=FindProcess(fileName);

    if(handleId==0)

    {

        printf("没有找到%s进程\n",fileName);

        return 0;

    }

    //EnumProcess();

    return 1;

}

你可能感兴趣的:(遍历)