检查程序进程是否存在/强制杀掉程序进程

时间:2021-04-13 22:35:21
#include <Windows.h>
#include <TlHelp32.h>

bool IsAppRunning()
{
    bool m_running = false;

    HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if (hSnapshot == INVALID_HANDLE_VALUE)
    {
        return m_running;
    }

    PROCESSENTRY32 pe = {0};
    pe.dwSize = sizeof(PROCESSENTRY32);
    if (!Process32First(hSnapshot, &pe))
    {
        CloseHandle(hSnapshot);
        return m_running;
    }

    while ( 1 )
    {
        if (!Process32Next(hSnapshot, &pe))
        {
            break;
        }

        if (lstrcmpi(pe.szExeFile, APP_PROG_NAME)==0)
        {
            m_running = true;
            break;
        }
    }

    CloseHandle(hSnapshot);

    return m_running;
}

int ShutDownApp()
{
    int result = -1;

    HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if (hSnapshot == INVALID_HANDLE_VALUE)
    {
        return result;
    }

    PROCESSENTRY32 pe = {0};
    pe.dwSize = sizeof(PROCESSENTRY32);
    if (!Process32First(hSnapshot, &pe))
    {
        CloseHandle(hSnapshot);
        return result;
    }

    while ( 1 )
    {
        if (!Process32Next(hSnapshot, &pe))
        {
            break;
        }

        if (lstrcmpi(pe.szExeFile, APP_PROG_NAME)==0)
        {
            HANDLE process = OpenProcess(PROCESS_TERMINATE, 0, pe.th32ProcessID);
            if (process)
            {
                result = 0;
                TerminateProcess(process, 0);
                CloseHandle(process);
            }
        }
    }

    CloseHandle(hSnapshot);
    ::Sleep(100);

    return result;
}