Friday, June 11, 2010

TerminateProcess in WM6 (C++)

BOOL KillAProcess(CString csName)
{
BOOL bRetVal = TRUE;
//HANDLE hPID;

HANDLE h_pro;
HANDLE h_sna;
PROCESSENTRY32 pe_sen = {0};
bool lpFound = false;
int result;

CString csMsg;
CString cMethod = L"KillAProcess";

h_sna = CreateToolhelp32Snapshot(
TH32CS_SNAPPROCESS|TH32CS_SNAPNOHEAPS, 0);
//A snapshot tries to reserve 1MB of virtual memory. If it can't, or can't
//commit the first page (or n pages), then you'll get ERROR_NOT_ENOUGH_MEMORY
//and very important, to add the TH32CS_SNAPNOHEAPS, to limit the ammount of
//data the snapshot generates


if ((HANDLE) -1 == h_sna)
{
DWORD lngResult = GetLastError();
CString csError;
csError.Format(L"CreateToolhelp32Snapshot failed=%d",lngResult);
AfxMessageBox(csError);

}

pe_sen.dwSize = sizeof(PROCESSENTRY32);

if (Process32First(h_sna, &pe_sen))
{
do
{
h_pro = OpenProcess (PROCESS_ALL_ACCESS, FALSE, pe_sen.th32ProcessID);
CloseHandle (h_pro);

//AfxMessageBox(pe_sen.szExeFile);

if (pe_sen.th32ProcessID != 0)
{
result = _tcscmp(pe_sen.szExeFile,csName);

if(result==0)
{
//hPID = (HANDLE)pe_sen.th32ProcessID;
lpFound = true;

//start kill
HANDLE hProcess = NULL;
hProcess = ::OpenProcess(PROCESS_TERMINATE, FALSE, pe_sen.th32ProcessID);
//********************
//NOTE!!!!Have to have this Openprocess before TerminateProcess call to make it work.
//************************

if (hProcess != NULL)
{
if (::TerminateProcess(hProcess, 0))
{
csMsg.Format(L"%s: killed %s", cMethod, csName);
AfxMessageBox(csMsg);
}
else
{
csMsg.Format(L"%s: error terminating %s [0x%08x]", cMethod,
csName, GetLastError());
AfxMessageBox(csMsg);
}
}
if (hProcess != NULL)
{
::CloseHandle(hProcess);
hProcess = NULL;
}

break;
}
}
} while (Process32Next(h_sna, &pe_sen));
}else
AfxMessageBox(L"Process32First failed");


return bRetVal;
}

No comments: