WinCE根据进程名称杀进程

WinCE根据进程名称杀进程

220人阅读 评论(0) 收藏 举报

This is a function which I used to kill the process, it is usefull in our test. I write it down here in case I forget it.

 

#include <windows.h>

#include <Tlhelp32.h>

 

#define MAX_STR 256

 

/// <summary>
///  Function to kill the process by its name
/// </summary>
/// <param name="lpProcessName">The process name</param>
/// <returns>
///   HRESULT:
///     S_OK if killed the prcess successfully
///     E_FAIL if any error occurs
/// </returns>
HRESULT KillProcessByName(LPCTSTR lpProcessName)
{

    HRESULT hr = S_OK;
    HANDLE hnd;
    PROCESSENTRY32 pe32;

 

    if (NULL == lpProcessName)
    {
        return E_INVALIDARG;
    }

 

    //Takes a snapshot of the processes
    hnd = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,NULL);
    if(hnd == INVALID_HANDLE_VALUE)
    {
        DEBUGMSG(TRUE, TEXT("KillProcessByName: INVALID_HANDLE_VALUE"));
        return E_FAIL;
    }

 

    pe32.dwSize = sizeof(pe32);

 

    //enumerate the processes
    BOOL bMore = Process32First(hnd,(LPPROCESSENTRY32)&pe32);


    while(bMore)
    {
        _TCHAR aCompareProcessName[MAX_STR];
        _tcscpy_s(aCompareProcessName,MAX_STR,pe32.szExeFile);
        _tcslwr_s(aCompareProcessName,MAX_STR);

 

        //Do: compare the process with the name
        if(lstrcmp(lpProcessName,aCompareProcessName)==0)
        {
            DEBUGMSG(TRUE, (TEXT("The Process:%s with ID: %X will be killed"),
                pe32.szExeFile,
                pe32.th32ProcessID));

 

            //Get the handler
            HANDLE h_ProcessHandle = OpenProcess(
                PROCESS_ALL_ACCESS,
                FALSE,
                pe32.th32ProcessID);

 

            if(NULL == h_ProcessHandle)
            {
                DEBUGMSG(TRUE, TEXT("ERROR: The Process should already exit"));
                CloseToolhelp32Snapshot(hnd);
                hr = S_OK;
                break;
            }

 

            DWORD exitCode =0;


            //Terminate the process
            if(!TerminateProcess(h_ProcessHandle,exitCode))
            {
                LogOut(LOG_FAIL, TEXT("ERROR: Fail to terminate process: %X for Error:%d"),
                    pe32.th32ProcessID,exitCode);
                hr = E_FAIL;
                break;
            }
        }//end of do

 

        bMore = ::Process32Next(hnd,(LPPROCESSENTRY32)&pe32);
    }// End of while

 

    //closes a handle to a snapshot.
    CloseToolhelp32Snapshot(hnd);
    return hr;
}

你可能感兴趣的:(function,kill,null,Access,WinCE)