2010年1月31日 星期日

CuToolhelp - Takes a snapshot of the specified processes

//  Takes a snapshot of the specified processes




// CuToolhelp.h


class CuToolhelp  
{
    HANDLE  m_hSnapshot;

public:
    CuToolhelp();
    virtual ~CuToolhelp();

    BOOL CreateSnapshot(DWORD dwFlags, DWORD dwProcessID = 0);
    void CloseSnapshot();

    BOOL ProcessFirst(PPROCESSENTRY32 ppe) const;
    BOOL ProcessNext(PPROCESSENTRY32 ppe) const;
    BOOL ProcessFind(DWORD dwProcessID, PPROCESSENTRY32 ppe) ;
    BOOL ProcessFind(wstring strExeFile, PPROCESSENTRY32 ppe) ;
};


// CuToolhelp.cpp



CuToolhelp::CuToolhelp()
:m_hSnapshot(INVALID_HANDLE_VALUE)
{

}

CuToolhelp::~CuToolhelp()
{
    CloseSnapshot();
}

BOOL CuToolhelp::CreateSnapshot(DWORD dwFlags, DWORD dwProcessID)
{
    CloseSnapshot();

    if( dwFlags == 0 )
    {
        m_hSnapshot = INVALID_HANDLE_VALUE;
    }
    else
    {
        m_hSnapshot = CreateToolhelp32Snapshot(dwFlags, dwProcessID);
    }

    return (m_hSnapshot != INVALID_HANDLE_VALUE);

}

void CuToolhelp::CloseSnapshot()
{
    if( m_hSnapshot != INVALID_HANDLE_VALUE )
        CloseToolhelp32Snapshot(m_hSnapshot);
}

BOOL CuToolhelp::ProcessFirst(PPROCESSENTRY32 ppe) const
{
    BOOL fOk = ::Process32First(m_hSnapshot, ppe);

    // Remove the "[ System Process]" (PID = 0)
    if( fOk && (ppe->th32ProcessID == 0 ))
        fOk = ProcessNext(ppe);

    return (fOk);
}

BOOL CuToolhelp::ProcessNext(PPROCESSENTRY32 ppe) const
{
    BOOL fOk = ::Process32Next(m_hSnapshot, ppe);

    // Remove the "[ System Process]" (PID = 0)
    if( fOk && (ppe->th32ProcessID == 0 ))
        fOk = ProcessNext(ppe);

    return (fOk);
}

BOOL CuToolhelp::ProcessFind(DWORD dwProcessID, PPROCESSENTRY32 ppe) 
{

    BOOL bFound = FALSE;
    for( BOOL fOk = ProcessFirst(ppe); fOk; fOk = ProcessNext(ppe) )
    {
        bFound = ( ppe->th32ProcessID == dwProcessID );
        if( bFound )
            break;
    }

    return (bFound);

}
BOOL CuToolhelp::ProcessFind(wstring strExeFile, PPROCESSENTRY32 ppe) 
{

    BOOL bFound = FALSE;
    for( BOOL fOk = ProcessFirst(ppe); fOk; fOk = ProcessNext(ppe) )
    {
        bFound = (strExeFile == ppe->szExeFile);
        if( bFound )
            break;
    }
    return (bFound);

}

沒有留言:

張貼留言