WinCE根据进程名称杀进程

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;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值