浮萍晓生的开发日志

记录学习的旅程,把握可预见的未来

导航

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

Posted on 2013-12-18 16:14  浮萍晓生  阅读(252)  评论(0编辑  收藏  举报
#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;
}