Kill a process given its executable name.

0.00 avg. rating (0% score) - 0 votes

BOOL KillProcessByName(const TCHAR* p_strEXE)
{
printf(“Attempting to terminate “);
OutputDebugString(p_strEXE);
printf(“n”);

HANDLE hSnapShot = NULL;
PROCESSENTRY32 pEntry
= {0};

// Get the snapshot of the system
hSnapShot
= CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (hSnapShot != INVALID_HANDLE_VALUE)
{
pEntry
.dwSize = sizeof(pEntry);

//Get first process
if (Process32First(hSnapShot, &pEntry))
{
TCHAR strTempExe
[MAX_PATH];
_tcscpy(strTempExe, pEntry.szExeFile);

printf(“Found: “);
OutputDebugString(strTempExe);
printf(“n”);

//found process on the first attempt, kill it
if (_tcscmp(strTempExe, p_strEXE) == 0) goto KillProcess;

//Iterate through all other processes
while (Process32Next(hSnapShot, &pEntry))
{
_tcscpy(strTempExe, pEntry.szExeFile);

printf(“Found: “);
OutputDebugString(pEntry.szExeFile);
printf(“n”);

//we have found our process;
if (_tcscmp(strTempExe, p_strEXE) == 0) goto KillProcess;
}
}
else
{
printf(“Process32First FAILED. Error %dn”, GetLastError());
}
}
else
{
printf(“Process32First FAILED. Error %dn”, GetLastError());
}

//if we are here it means process cannot be found;
goto ProcessNotFound;

KillProcess:

CloseHandle(hSnapShot);

//kill it
HANDLE hProcess
= OpenProcess(PROCESS_ALL_ACCESS, FALSE, pEntry.th32ProcessID);
if (hProcess)
{
if (::TerminateProcess(hProcess, 0))
{
printf(“Process terminated.n”);
return TRUE;
}
else
{
printf(“TerminateProcess FAILED. Error %dn”, GetLastError());
return FALSE;
}
}
else
{
printf(“OpenProcess FAILED. Error %dn”, GetLastError());
return FALSE;
}

ProcessNotFound:
CloseHandle(hSnapShot);

printf(“Specified process not found.n”);
return FALSE;
}

0.00 avg. rating (0% score) - 0 votes
ToughDev

ToughDev

A tough developer who likes to work on just about anything, from software development to electronics, and share his knowledge with the rest of the world.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>